Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda