[英]Wrap each line with li
This is how I split the content of a textarea element into br-lines for displaying: 这就是我将textarea元素的内容拆分为br行以显示的方式:
function linebreak(string) {
return string.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
So this string... 所以这个字符串...
Line 1\nLine 2
...gets... ...得到...
Line 1<br>
Line 2<br>
But now I need each line wrapped as a li
-element. 但是现在我需要将每行包装为
li
元素。 The result should be: 结果应为:
<li>Line 1</li>
<li>Line 2</li>
This is how I would do that: 这就是我要做的:
let result = '';
string.split('\n').forEach(function(line) {
result += '<li>' + line + '</li>';
});
return result;
But is this the correct way to do that? 但这是正确的方法吗?
You can replace any sequence of non-linebreaks with <li>...</li>
. 您可以用
<li>...</li>
替换任何非换行符序列。 Note that this also ignores empty lines: 请注意,这也将忽略空行:
var text = 'first line\\nsecond line\\r\\n\\r\\nthrid\\n\\n\\n' html = text.replace(/[^\\r\\n]+/g, '<li>$&</li>'); console.log(html)
You can use Array#map
and Array#join
method to make it one linear 您可以使用
Array#map
和Array#join
方法使其线性
return string.split('\n').map(function(line) { return '<li>' + line + '</li>'; }).join('');
Or something tricky with Array#join
method 或使用
Array#join
方法有些棘手的事情
return '<li>' + string.split('\n').join('</li><li>') + '</li>';
Here you go, you can use split
to split your value into array then with reduce
wrap each one of them into a span/li whatever you want. 在这里,您可以使用
split
将您的值拆分为数组,然后使用reduce
将它们中的每一个拆分为span / li(无论您想要什么)。
function wrapValue() { var string = document.getElementById("textarea").value // append to ul document.getElementById("myList").innerHTML = linebreak(string); } function linebreak(string){ return string.split('\\n') .reduce(function(c, n){ return c + '<li>' + n + ' </li>' }, '') }
<textarea id="textarea" name="" id="" cols="30" rows="10"></textarea> <button onclick="wrapValue()">Clic</button> <ul id="myList"> </ul>
Or more shorter with fat arrow functions 或更短的带有胖箭头功能
wrapValue = () => {
var string = document.getElementById("textarea").value
// append to ul
document.getElementById("myList").innerHTML = linebreak(string);
}
linebreak = (string) => string.split('\n')
.reduce((c, n) => c + '<li>' + n + ' </li>', '');
You can try string.replace
as well. 您也可以尝试使用
string.replace
。
function getLIs(str) { return "<li>" + str.replace(/\\n/g, "</li><li>") + "</li>"; } var str = "Line 1\\nLine 2\\nLine 3"; document.getElementById("content").innerHTML = getLIs(str);
<ul id="content"></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.