stack
stack

Reputation: 10228

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 other word, I'm trying to remove all white spaces between a specific range of such a string.


Also Here is what I have tried:

(start:)(?:(\S+)(\s+))(.*)(?= some)

It works as well, but I should execute it several times to achieve expected result .. How can I use \1+ in my regex to run it several times?

Upvotes: 0

Views: 48

Answers (2)

anubhava
anubhava

Reputation: 786031

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

Upvotes: 2

Barmar
Barmar

Reputation: 782407

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

Upvotes: 3

Related Questions