Jon Sud
Jon Sud

Reputation: 11641

How to split a string correctly by array of double curly brackets in js regex?

I have a regex that matches the words with double curly brackets:

    let str = 'This is a {{test}} string with {{multiple}} matches.';
    let regex = /\{\{(.+?)\}\}/g;
    let matches = str.match(regex);
    console.log(matches); // ['{{test}}', '{{multiple}}']

Now I want to split str into chunks by matches array:

 let regex2 = new RegExp(`\\b${matches.join('|')}\\b`, 'gi');
 let substrings = str.split(regex2);
 console.log(substrings);

But the output of substrings is "This is a {{test}} string with {{multiple}} matches.".

What I was expected is: ["This is a ", "{{test}}", " string with ", "{{multiple}}", "matches."]

But I know my regex is correct because if I do it without using those double curly brackets, it works. but I must need to use them to get what I want.

So why regex doesn't split them as I was expecting? how can I change the code so that it will work as expected?

Upvotes: 0

Views: 167

Answers (1)

samuellawrentz
samuellawrentz

Reputation: 1732

You can achieve that by using the paranthesis () outside the whole group. Doing so, will include the separator in the result.

Try this regex - /({{.+?}})/g

const str = "This is a {{test}} string with {{multiple}} braces"
console.log(str.split(/({{.+?}})/g))

Basically, If separator is a regular expression that contains capturing parentheses ( ), matched results are included in the array.

Upvotes: 2

Related Questions