How To Execute A Capturing Group Multiple Times?
I have this string: var str = 'some text start:anything can be here some other text'; And here is expected result: //=> some text start:anythingcanbehere some other text In ot
Solution 1:
You can't do what you want with a simple regexp replace, because a capture group can only capture one string -- there's no looping. Javascript allows you to provide a function as the replacement, and it can perform more complex operations on the captured strings.
var str = "some text start:anything can be here some other text";
var newstr = str.replace(/(start:)(.*)(?= some)/, function(match, g1, g2) {
return g1 + g2.replace(/ /g, '');
});
alert(newstr);
Solution 2:
Using replace
with a callback:
var repl = str.replace(/(start:.*?)(?= some\b)/, function(_, $1) {
return $1.replace(/\s+/g, ''); });
//=> some text start:anythingcanbehere some other text
Post a Comment for "How To Execute A Capturing Group Multiple Times?"