I have a string template with few dynamic keywords like:
I am {{name}} from {{city}}
For a given input string I want to match it against the template and extract the name and city from the input in Javascript.
Eg. input I am Alex from Paris
should give me name as Alex and city as Paris.
Is there some standard way of performing such operations in Javascript ?
CodePudding user response:
If you have control over your template, you can make it a regular expression to use named capturing groups (?<groupName>)
, and then use .match()
on your string to obtain the matched groups:
const template = /^I am (?<name>[^ ] ) from (?<city>[^ ] )$/;
const str = "I am Alex from Paris";
const {groups} = str.match(template);
console.log(groups);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
You could parse your template to the above regular expression also if you need to keep it as a string, but you may need to escape it if the template is provided by a user. Small example:
const templateToRegExp = (strTemplate) => {
const regTemp = strTemplate.replace(/{{([^}}] )}}/g, "(?<$1>[^ ] )");
return new RegExp(`^${regTemp}$`);
}
const template = "I am {{name}} from {{city}}";
const regexp = templateToRegExp(template);
const str = "I am Alex from Paris";
const {groups} = str.match(regexp);
console.log(groups);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
One approach could be to use regular expressions. Since you already know the structure of the string, you could group parts of the string together and always extract the same part. One downside is that you need to update the regex every time you update the template string.
For example:
Using the following regex:
^(I am )(.*)( from )(.*)$
Will result in 4 groups. The second group will be the value for the name and the fourth group will be the value for the city
See it in action with some examples at https://regex101.com/r/7tl7Ap/1
CodePudding user response:
we use template literals in such cases. Instead of using single or double quotes defines the string with (`) and pass the variable with a dollar sign ($)
For example:
`I am ${name} from ${city}`
CodePudding user response:
var string = 'my name is var';
var data = 'pratik';
console.log(string.replace("var", data))
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>