Search code examples
javascriptarraysregexsplit

How to split strings with regex like {{(all spaces)variableValue(all spaces)}}


It is necessary to split the strings according to such a regex, but I cannot compose it.

Introductory line:

{{ text1  }} 123 {{text1}}{{text1}}  {{  text1}}134

Text in a variable:

const a = text1;

Split result:

["{{text1}}"," 123 ","{{text1}}","{{text1}}","  ","{{text1}}","134"]

Also, keep in mind that the word text1 is just the value of a variable that can change.

I tried to do it through new Regexp to insert the value of the variable there, but I still couldn’t do a normal split.


Solution

  • This one does not care what word is in the brackets

    If you really want the space in element 4, we will need to test for one space before trimming

    https://regex101.com/r/RMEeRd/1

    const input = `{{ text1  }} 123 {{text1}}{{text1}}  {{  text1}}134`;
    const regex = /\{\{\s*([^}]+)\s*\}\}|([^{}]+)/g;
    const matches = [...input.matchAll(regex)].map(match => match[0].trim());
    console.log(matches)