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...
CodePudding user response:
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') );
CodePudding user response:
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);