4

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.

2
  • Why do you need ajax for that if you know the exact strings you want to replace? Commented Dec 29, 2016 at 12:51
  • 1
    As a programmer, I really like a generic solution. But generic examples are some times hard to grasp, and might confuse the reader. So, while I'm looking for a generic solution, I find it more appropriate to give an example in a more specific manner. Commented Dec 29, 2016 at 13:07

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@torazaburo - You are right, but that's a style choice. { and } are metacharacters, and I usually like to escape them. This is even more justifiable here, in the context of numbers. {\d+} might become {2}, for example in a test or modified code, resulting in a syntax error.
Thanks. This solution seems to require that you know in advance that there are two strings to be replaced ({0} and {1}). What if the number of strings to be replaced is unknown, meaning there could be {2}, {3}, {4}, ...?
@IanY. - this should work for any number as long as you supply the right arr - which could be create dynamically. The first two lines here are copied from the question so I'll have runnable code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.