Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace words in string with values of string array

I have the following string with placeholders

'test {{1}} this {{2}} {{3}}'

these placeholders later should be replaced in same order by the values from input fields

['now', 'code', 'block']

so the final string looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'test now this code block'

what’s the best approach here?

>Solution :

You can use .replace() on your string with a regular expression to match the digits between the {{ and }} characters. Then, using the replacement function, which will fire for each digit that is matched, you can return the new value to replace the {{N}} occurrence with, which will be the value of the current digit -1 from your array of values.

const arr = ['now', 'code', 'block']; 
const str = 'test {{1}} this {{2}} {{3}}';
const res = str.replace(/{{([^}}]+)}}/g, (_, d) => arr[d-1]);

console.log(res);

Regex explanation for /{{([^}}]+)}}/g:

  • {{ – Match the literal characters {{ in your string
  • ([^}}]+) – Continue matching one or more characters that aren’t }} and capture them in a group (the ( and ) forms a capturing group for your digit)
  • }} – match the literal }} characters
  • /g – The global flag means match all occurrences of this pattern throughout your string.

In this case, the first argument to the replacement function is the entire match itself (ie: {{N}}) which we ignore with _, and the second argument is the capturing group we formed that has your digit.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading