简体   繁体   中英

Replace Space with Newline in JavaScript?

I need to create a new line after each <li> element. I stripped the <li> of spaces using /\\s*<li>/g , but it's not working like I want it to work.

Here is the jsFiddle .

For example:

Processing this text using doIt(){...}

<ol>
 <li>Hello world! :)</li> 
  <li>Hello how are you</li> 
   <li>good</li>
</ol>

I used /\\s*<li>/g to remove any amount of space before <li> , and it gives you:

1. Hello world! :)2. Hello how are you3. good

Is there a way to make the above, look like:

1. Hello world! :)
2. Hello how are you
3. good

Here is doIt(){...}

function doIt() {
var input = document.getElementById('input');
var olPatt = /<ol>\s*((?:<li>.+<\/li>\s*)+)<\/ol>/g;
var i = 1;

input.value = input.value.replace(olPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function() {return i++ + '.' + ' ';}).replace(/<\/li>/g, '');
});

input.value = input.value.replace(ulPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function () {
    return i++ + '.' + ' ';
    }).replace(/<\/li>/g, '');
});
}

In your fiddle code,

replace your this line , return listItems.replace(/\\s*

  • /g, function() {return i++ + '.' + ' ';}).replace(/</li>/g, '');

    by this line, return listItems.replace(/\\s*

  • /g, function() {return i++ + '.' + ' ';}).replace(/</li>/g, '\\n')

    It will give you line break after 1, 2 & 3...

  • LOL fixed it.

    I need to apply '\\n' to .replace(/<\\/li>/g, '\\n');

    input.value = input.value.replace(olPatt, function (n, listItems) {
        return listItems.replace(/\s*<li>/g, function() {return i++ + '.' + ' ';}).replace(/<\/li>/g, '\n');
    });
    

    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.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM