Replace words in string with values of string array

Advertisements

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

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

Leave a ReplyCancel reply