在JavaScript中用Newline替换空格?

时间:2014-06-28 07:05:00

标签: javascript jquery regex

我需要在每个<li>元素之后创建一个新行。我使用<li>删除了/\s*<li>/g个空格,但它不能像我希望的那样工作。

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

2 个答案:

答案 0 :(得分:1)

在你的小提琴代码中,

替换你的这条线, return listItems.replace(/ \ s *

  • / g,function(){return i ++ +'。'+'';}}。replace(/&lt; / li&gt; / g,'') ;

    这条线, return listItems.replace(/ \ s *

  • / g,function(){return i ++ +'。'+'';}}。replace(/&lt; / li&gt; / g ,'\ n')

    它会在1,2和2之后给你换行。 3 ...

  • 答案 1 :(得分:0)

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