Sha*_*deh 1 javascript regex jquery
我有一个像这样的字符串:
var str = "some text is here
- first case
- second case
- third case
some text is here";
Run Code Online (Sandbox Code Playgroud)
现在我需要这个输出:
var newstr = "some text is here
1. first case
2. second case
3. third case
some text is here";
Run Code Online (Sandbox Code Playgroud)
我所能做的就是删除那些-.现在我需要$1用动态数字替换......这可能吗?
像这样的东西:
.replace (/(^\s*-\s+)/gm, "{A dynamic number which is ascending}. ")
Run Code Online (Sandbox Code Playgroud)
您可以使用String#replace回调和计数器.
使用ES2015 箭头功能:
str.replace(/^\s*- /gm, () => counter++ + '. ');
Run Code Online (Sandbox Code Playgroud)
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 purposeRun Code Online (Sandbox Code Playgroud)
ES5中的等效代码
str.replace(/^\s*- /gm, function() {
return counter++ + '. ';
});
Run Code Online (Sandbox Code Playgroud)
正则表达式/^\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 purposeRun Code Online (Sandbox Code Playgroud)