Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 770
Genzotto Avatar asked Dec 29 '25 17:12

Genzotto


1 Answers

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.

like image 162
Yury Tarabanko Avatar answered Jan 01 '26 07:01

Yury Tarabanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!