简体   繁体   中英

JS string: Replace with index in regex

I have little to no experience with regex, and I was wondering how you would go about to replace a section in a string identified by regex, where the index is part of the identified section?

Here is my example string:

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

This is my data array:

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

Now, with replace and regex, I would like to match the index in the {#} section with the array element matching the index.

Resulting string:

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

Notice how it would ignore the {n}, as 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 bit harder to read :)

Thanks in advance.

You can use replace with a callback :

 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); 

The pattern is simple - it matches a number inside curly braces, and captures the number to group number 1.
The callback function parses the number (which is not strictly required, but arr["1"] is not pretty), and then return the proper element from the array.
The callback could use some more error checking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM