javascript - Replace all specific characters with counter ascending? -
i have string this:
var str = "some text here - first case - second case - third case text here"; now need output:
var newstr = "some text here 1. first case 2. second case 3. third case text here"; all can removing -. need replace $1 dynamic number... possible?
something this:
.replace (/(^\s*-\s+)/gm, "{a dynamic number ascending}. ")
you can use string#replace callback , counter.
using es2015 arrow function:
str.replace(/^\s*- /gm, () => counter++ + '. '); var str = `some text here - first case - second case - third case text here`; var counter = 1; str = str.replace(/^\s*- /gm, () => counter++ + '. '); console.log(str); document.write(str); // demo purpose equivalent code in es5
str.replace(/^\s*- /gm, function() { return counter++ + '. '; }); the regex /^\s*- /gm, match lines starting number of spaces followed hyphen.
var str = `some text here - first case - second case - third case text here`; var counter = 1; // initialize counter str = str.replace(/^\s*- /gm, function() { return counter++ + '. '; // incrementing counter after using value }); console.log(str); document.write(str); // demo purpose
Comments
Post a Comment