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


Of course have

url = url.replace(/\$(\d)/g, function(_, i) {
   return params[i];
});

      



UPD (pedantic mode): As @ undefined pointed out, there is still a loop. But implicit, implemented by a function String.prototype.replace

for flagged regular expressions g

.

+4


source


Use the replace function:

var url = "http://my.url/$1/$2/$3";
var params = [ "first", "second", "third"];

url = url.replace (/\$(\d)/g, function(a,b) { return params[Number(b)-1]; });

      



As you can see, there is no need to use an "unused" element.

+2


source







All Articles