用计数器升序替换所有特定字符?

时间:2016-01-28 11:02:45

标签: javascript jquery regex

我有一个这样的字符串:

var str = "some text is here
            - first case
            - second case 
            - third case
           some text is here";

现在我需要这个输出:

var newstr = "some text is here
                1. first case
                2. second case 
                3. third case
               some text is here";

我所能做的就是removing those -。现在我需要用动态数字替换$1 ......这可能吗?

这样的事情:

.replace (/(^\s*-\s+)/gm, "{A dynamic number which is ascending}. ")

2 个答案:

答案 0 :(得分:5)

您可以将String#replace与回调和计数器一起使用。

使用ES2015 Arrow function

str.replace(/^\s*- /gm, () => counter++ + '. ');



var str = `some text is here
                - first case
                - second case 
                - third case
               some text is here`;

var counter = 1;
str = str.replace(/^\s*- /gm, () => counter++ + '. ');

console.log(str);
document.write(str); // Demo purpose




ES5中的等效代码

str.replace(/^\s*- /gm, function() {
    return counter++ + '. ';
});

正则表达式/^\s*- /gm将匹配以任意数量的空格开头,后跟连字符的所有行。



var str = `some text is here
            - first case
            - second case 
            - third case
           some text is here`;

var counter = 1; // Initialize the counter

str = str.replace(/^\s*- /gm, function() {
  return counter++ + '. '; // Incrementing counter after using its value
});

console.log(str);
document.write(str); // Demo purpose




答案 1 :(得分:0)

你可以使用它。

var i=1;
while(str.indexOf("-")!=-1)
    str=str.replace(/-/,i++ +".")