Regex replace in Javascript
I have the following items:
var url = "http://my.url/$1/$2/$3";
var params = ["unused", "first", "second", "third"];
I want to replace every $ n element in the url for the element at position n in the params array (ie $ 1 will be "first", $ 2 will be "second" and 3 will be "third").
I have the following code:
var cont=1;
while (params[cont]) {
url = url.replace(new RegExp("\\$" + cont, "gm"), params[cont])
cont++
}
The above code works, but I am wondering if there would be a better way to accomplish this replacement (without a loop).
Thank you in advance
+3
source to share
2 answers