audoh
audoh

Reputation: 81

Get array of both matches and non-matches

What I want to do is split up a string into an array of multiple contiguous substrings, alternating between matches and non-matches of a given regular expression.

Like this:

[nonmatch, match, nonmatch, match...]

For example, with the right regex (the actual expression being not important here),

"I [went to the doctor] today to [eat some] food"

might become:

["I ", "[went to the doctor]", " today to ", "[eat some]", " food"]

I need to do this because I need to take out some parts of a string temporarily, do some stuff to the rest of the string, and then insert the previous parts back where they were to make the string whole again (by simply combining the entire array into a string).

All I can find from searching are people who want to either get rid of some of the string (e.g. the [] in the example above) or join some non-matches and matches together, like:

["I ", "[went to the doctor] today to ", "[eat some] food"]

Upvotes: 1

Views: 463

Answers (1)

trincot
trincot

Reputation: 350270

You can use split for that, passing it a regular expression that has a capture group (i.e. parentheses). Then this delimiting part will also be included in the resulting array:

var s = "I [went to the doctor] today to [eat some] food"
var result = s.split(/(\[.*?\])/);
console.log(result); 

The matches will always be at the odd indexes of the resulting array.

Upvotes: 8

Related Questions