Freezer freezer
Freezer freezer

Reputation: 120

Simple JS regex replace.

I am struggling trying to create a really simple RegExp. (probably lacking some hours of sleep).

I just have has an input this string : /users/10/contracts/1 My regex is this one : /users/(\w+)/contracts/(\w+)/

I want to replace all matches with this kind of string : /users/{variable1}/contracts/{variable2}

Here is my complete source code :

var customRegex = "/users/(\\w+)/contracts/(\\w+)";
  var i =0;
  var finalUrl = "/users/1234/contracts/5678".replace(new RegExp(customRegex, 'gi'), function myFunction(x, y){
    return "{variable" + i + "}"; 
  });

  console.log(finalUrl);

Could you please help me?

I wish you a nice day and thank you for your help.

Upvotes: 1

Views: 72

Answers (2)

Julio Betta
Julio Betta

Reputation: 2295

If you need to match the numbers only, it should do the work.

var finalUrl = "/users/1234/contracts/5678";

finalUrl.match(/\d+/g).forEach(function(v, i) { 
  finalUrl = finalUrl.replace(v, "{variable" + (i + 1) + "}"); 
});

document.write(finalUrl);

Upvotes: 0

Jens
Jens

Reputation: 555

The replace-function is only called once for the whole replacement. You are using 2 matchers so you also get 2 matches as parameters in the callback-function.

var customRegex = "/users/(\\w+)/contracts/(\\w+)";
var finalUrl = "/users/1234/contracts/5678".replace(new RegExp(customRegex, 'gi'), function myFunction(wholeString, p1, p2){
    return wholeString.replace(p1, "{variable1}").replace(p2, "{variable2}"); 
});
console.log(finalUrl);

Upvotes: 3

Related Questions