将所有特定字符替换为计数器升序



我有一个这样的字符串:

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";

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

像这样:

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

String#replace与回调和计数器一起使用。

使用 ES2015 箭头功能:

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

你可以

使用它。

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

最新更新