skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. You can achieve this using a loop that iterates over the items in the array:

    let text = 'test {{1}} this {{2}} {{3}}';
    const keywords = ['now', 'code', 'block'];
    
    for (let i = 1; i < keywords.length + 1; i++) {
      text = text.replace(`{{${i}}}`, keywords[i-1]);
    }
    
    console.log(text);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search