Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Javascript String template parsing for keywords

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 ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

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

about 4 years ago · Juan Pablo Isaza Report

0

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}`

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!