1

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.

1

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

You don't need i flag because \w matches both uppercase and lowercase alphabets
Thank you Jens. It was exactly what i wanted :)
@Tushar indeed, just copied it from his question. Maybe he simplified his question and is using a more complex pattern but for this one you are completly right, good hint.
0

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);

1 Comment

You don't need i flag for numbers. Never heard of (upp|low)erCase numbers. :P

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.