Genzotto
Genzotto

Reputation: 1974

Regex replace in Javascript

I have the following elements:

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

I want to replace each $n element in the URL for the element in position n in the params array (i.e. $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 wonder if there would be a better way to do this replace (without looping).

Thank you very much in advance

Upvotes: 3

Views: 95

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Sure there is

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

UPD (pedantic mode): As @undefined pointed out there is still a loop. But an implicit one implemented by String.prototype.replace function for regexps having g flag on.

Upvotes: 4

Jongware
Jongware

Reputation: 22478

Use a 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 a "unused" element.

Upvotes: 2

Related Questions