ngen
ngen

Reputation: 8966

Javascript string variable with regex

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'.

Upvotes: 0

Views: 392

Answers (1)

lonesomeday
lonesomeday

Reputation: 237827

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.

Upvotes: 3

Related Questions