Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda