Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
How can I parse a string with double curly brackets, using JavaScript?

Is there a fast regex method or similar that can take a string and parse it into bits not in double-curly brackets (let's call those "static") and bits that are in double-curly brackets (let's call those "dynamic")?

For example, input:

Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.

Required output:

[
  {
    type: "static",
    value: "Lorem "
  },
  {
    type: "dynamic",
    value: "ipsum dolor sit"
  },
  {
    type: "static",
    value: " amet, {consectetur} adipiscing "
  },
  {
    type: "dynamic",
    value: "elit"
  },
  {
    type: "static",
    value: "."
  },
]

My best try so far has been to use /\{*([^{}]+)\}*/g as a regex and loop through using while and exec but it incorrectly identifies any number of curly brackets as dynamic values, as shown here:

function templateParser(string) {
  const re = /\{*([^{}]+)\}*/g;

  const output = [];

  while (true) {
    const match = re.exec(string);

    if (!match) {
      break;
    }

    const [templateItem, templateKey] = match;

    output.push({
      type: templateItem === templateKey ? "static" : "dynamic",
      value: templateItem === templateKey ? templateItem : templateKey
    });
  }

  return output;
}

console.log(
  templateParser(
    "Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}."
  )
);

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

To distinguish {{ this }} from that an idea to capture this but match that.

{{(.*?)}}|.+?(?={{|$)
  • The left side of the alternation captures "dynamic" matches to the first group.
  • On the right side "static" parts get matched until the next {{ or up to the end.

See this demo at regex101 or the JS-demo at tio.run

Using exec your values can easily be set according e.g. m[1]!=null (first group matched). Of course this is related to your sample data. Assuming there is no nesting and not guessing anything else.

about 4 years ago · Santiago Gelvez Report

0

Edit: the other answer deserves the credit for using positive lookahead. Using that regex, the complete solution would be:

Array.from(s.matchAll(/{{(.*?)}}|.+?(?={{|$)/g))
  .map(e=>({type: e[1] ? 'dynamic' : 'static', value: e[1] ?? e[0]}))

or using named capturing groups:

Array.from(s.matchAll(/{{(?<dynamic>.*?)}}|(?<static>.+?)(?={{|$)/g))
  .flatMap(e=>Object.entries(e.groups))
  .filter(e=>e[1]).map(e=>({type: e[0], value: e[1]}))

Previous answer:

let s = `Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.`;
let result = [{a: 0, b: 0}, ...Array.from(s.matchAll(/{{.*?}}/g))
  .map(e=>({a: e.index, b: e.index+e[0].length}))]
  .map((e, i, arr) => [
    {type: 'dynamic', a: e.a, b: e.b},
    {type: 'static', a: e.b, b: i===arr.length-1 ? s.length : arr[i+1].a}
  ])
  .flat().map(o=>({type: o.type, value: s.substring(o.a, o.b)}))
  .filter(e=>e.value.length>0)
  .map(o=>o.type==='static' ? o :
    {type: 'dynamic', value: o.value.substring(2, o.value.length-2)});

What this does is find all of the strings contained within double braces, and then maps them to an array of objects with start and end indices a and b.

Those will be the dynamic ranges. We then fill in the gaps in the array to get the static ranges.

Finally, we clear the empty ranges and trim the double braces from the dynamic strings.

about 4 years ago · Santiago Gelvez Report

0

Now that I know more about what you are trying to do, this may help:

let mystring = 'test {{hello}} goodbye {{foo}} bar {foobar}';
let regex = /{{(.*?)}}/g;

console.log( mystring.match( regex ) );

output

["{{hello}}", "{{foo}}"]

it does a lazy match of each string that has double brackets, puts the matches in an array. You could then replace those substrings with modified versions that include the jsx tags, or something similar.

https://jsfiddle.net/u7gkz341/

Edit:

let mystring = 'test {{hello}} goodbye {{foo}} bar {foobar}';
let regex = /{{(.*?)}}/g;
let match;
let lastMatchIndex = 0;
let results = [];

while ( ( match = regex.exec( mystring ) ) !== null ) {
    results.push( mystring.substring( lastMatchIndex, match.index ) ); // adds static content up until match
    results.push( match[1] ); // adds dynamic matched content
    lastMatchIndex = regex.lastIndex;
}
results.push( mystring.substring( lastMatchIndex ) ); // adds static remainder of string
console.log( results );

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!