This is how I split the content of a textarea element into br-lines for displaying:
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. 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>
. 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
return string.split('\n').map(function(line) { return '<li>' + line + '</li>'; }).join('');
Or something tricky with Array#join
method
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.
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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.