3

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

2 Answers 2

4

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.

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

4 Comments

Strictly speaking this is a loop as well.
@undefined Atleast not an explicit one. I doubt one can do multiple replaces (of unknow number of tokens) without some sort of a loop.
Yes, and that's the answer of the question.
Your code worked and even using an implicit loop, I like it more than mine because of its simplicity. Thank you
2

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.

3 Comments

But this "unused" element is comming in my params array. It's an element that doesn't need to be replace but it's used to do an extra processing later, so it must be skipped in the replace process.
In that case you can use Yury's code. Without my adjustment it's totally similar.
Yours is good too (basically it's the same), but unfortunately two answers cannot be accepted... However, there's my upvote.

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.