0

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?

1
  • let regex2 = new RegExp(`(${matches.join('|')})`, 'i'); should suffice. Commented Dec 19, 2022 at 13:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.