JavaScript中的空格替换为换行符

Replace Space with Newline in JavaScript?

本文关键字:换行符 替换 空格 JavaScript      更新时间:2023-09-26

我需要在每个<li>元素之后创建一个新行。我使用/'s*<li>/g剥离了空格的<li>,但它不像我想要的那样工作。

这是jsFiddle。

例如:

使用doIt(){...}处理此文本

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

我使用/'s*<li>/g<li>之前删除任何数量的空间,它给你:

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

有没有办法让上面的内容看起来像:

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

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, '');
});
}

在您的代码中,

替换你的this行,返回listitem。替换(/'s*

  • /g,函数(){返回i++ + '。' + ';}).replace(/
  • /g, ");

    的这一行,返回listitem。替换(/'s*

  • /g,函数(){返回i++ + '。' + ';}).replace(/
  • /g, ''n')

    在1,2 &3…

    LOL修复了。

    我需要将''n'应用于.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');
    });