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

239
Visualizações
Extract values as placeholder variables in JavaScript

This is the opposite problem to Efficient JavaScript String Replacement. That solution covers the insertion of data into placeholders whilst this question covers the matching of strings and the extraction of data from placeholders.

I have a problem in understanding how to do the following in ES6 JavaScript.

I'm trying to figure out a way to match strings with placeholders and extract the contents of the placeholders as properties of an object. Perhaps an example will help.

Given the pattern:

my name is {name} and I live in {country}

It would match the string:

my name is Mark and I live in England

And provide an object:

{
  name: "Mark",
  country: "England"
}

The aim is to take a string and check against a number of patterns until I get a match and then have access to the placeholder values.

Can anyone point me in the right direction...

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would be surprised if it can be done with a regex.

The way I would think about it is as follows:

  • Split the template by { or }
  • iterate over the latter template parts (every other one starting with index 1)
  • In each iteration, get the key, its prefix, and postfix (or next prefix)
  • We can then compute the start and end indices to extract the value from the string with the help of the above.

const extract = (template, str) => {
  const templateParts = template.split(/{|}/);
  const extracted = {};

  for (let index = 1; index < templateParts.length; index += 2) {
    const 
      possibleKey = templateParts[index], 
      keyPrefix = templateParts[index - 1],
      nextPrefix = templateParts[index + 1];
      
    const substringStartIndex = str.indexOf(keyPrefix) + keyPrefix.length;
    const substringEndIndex = nextPrefix ? str.indexOf(nextPrefix) : str.length;
    
    extracted[possibleKey] = str.substring(substringStartIndex, substringEndIndex);
  }
  
  return extracted;
}

console.log( extract('my name is {name} and I live in {country}', 'my name is Mark and I live in England') );

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use named capture groups for that problem e.g.

const string = "my name is Mark and I live in England";
const regEx = /name is\s(?<name>\w+?)\b.*?live in (?<country>\w+?)\b/i;

const match = regEx.exec(string);
console.log(match?.groups);

about 4 years ago · Juan Pablo Isaza 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