JS string: replace with regex index

I have little experience with regular expressions, and I was wondering how you are going to replace the section in the string identified by the regular expression, where the index is part of the identified section?

Here is my sample line:

let exampleStr = "How do I {0} the {n} with the {1} in my array?";

This is my dataset:

let arr = ["replace", "items"];

Now, with the replacement and regex, I would like to map the index in the {#} section to the array element corresponding to the index.

Result line:

let result = "How do I replace the {n} with the items in my array?";

Note that it ignores {n} since it does not contain a numeric value.

I can do this with Array.indexOf, Number.isNaN, typeof, etc., but regex seems to be the β€œright” and cleaner way to do it, while a little harder to read :)

Thanks in advance.

+4
1

replace :

let exampleStr = "How do I {0} the {n} with the {1} in my array?";
let arr = ["replace", "items"];

let result = exampleStr.replace(/\{(\d+)\}/g, (g0, g1)=>arr[parseInt(g1,10)]);
console.log(result);
Hide result

- 1.
( , arr["1"] ), .
.

+3

Source: https://habr.com/ru/post/1665231/


All Articles