0

I can't understand why I can't use a variable for the regex string. See link: http://jsfiddle.net/nmWuw/1/

It works without the variable but not when a variable is used for the regex. I escaped my backslashes as well. Output should be '1,234,567,890'.

2
  • Sounds like someone needs to spend 2 minutes reading the documentation. Commented Jul 8, 2011 at 17:17
  • Proper demo: jsfiddle.net/simevidas/nmWuw/5 Commented Jul 8, 2011 at 17:21

1 Answer 1

3
var regex = "/\\d(?=(?:\\d{3})+(?!\\d))/g, '$&,'";

That is a string. It is not a regexp object and a replacement string. When it is passed to replace, it is one parameter, not two. You need to pass both parameters separately:

var regex = /\d(?=(?:\d{3})+(?!\d))/g;
var replace = '$&,';
var num = 1234567890;

alert(String(num).replace(/\d(?=(?:\d{3})+(?!\d))/g, '$&,'));
alert(String(num).replace(regex, replace));
alert(regex);

http://jsfiddle.net/nmWuw/3/


Note that you could define them in one call, if you really wanted to, using an array and apply:

var regex = [/\d(?=(?:\d{3})+(?!\d))/g, '$&,'];
alert(String.prototype.replace.apply(num, regex));

http://jsfiddle.net/nmWuw/6/

This is hardly a good idea, however -- it's much harder to read and much less intuitive.

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

1 Comment

Oh geez...I didn't even see that mistake. Brainfart on my part. Thanks.

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.