2

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...

0

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Works like a dream when run in stack overflow but when I try and run the same example in Deno I don't get the groups property. I'm assuming Deno has not yet implemented this.
@MarkTyers try console.log(match?.groups); when using typescript
1

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') );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.