Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}}."
  )
);
like image 882
Will Stone Avatar asked Sep 16 '26 00:09

Will Stone


2 Answers

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.

like image 107
bobble bubble Avatar answered Sep 18 '26 15:09

bobble bubble


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.

like image 34
Andrew Parks Avatar answered Sep 18 '26 14:09

Andrew Parks