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
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.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.Iterate through the array and replace using reg ex.
You can achieve this using a loop that iterates over the items in the array: