frequent
frequent

Reputation: 28503

how to use regex with variables instead of string?

Asked a few times, but I can't get it to work.

I'm doing a lot of these all over a script replacing various class names.

label.className.replace(/(?:^|\s)ui-icon-checkbox-on(?!\S)/g , ' ui-icon-globe');

and wanted to replace my replace call with a generic function which is being passed a string like ui-icon-checkbox-on and returns a regex object to handle my replace.

However, this is not working = it's not replacing anything:

var foo = function (className) {
  return new RegExp("(?:^|\s)" + className + "(?!\S)", "g");
};

label.className = label.className.replace(foo("ui-icon-checkbox-on"), ' ui-icon-globe');

And I'm at a loss trying to understand why.

Question:
How to correctly create a regex object, and use it to replace a string with another string?

Thanks!

PS: and no, I don't want to use jQuery to do it :-)

Upvotes: 0

Views: 116

Answers (2)

tea2code
tea2code

Reputation: 1007

Simple:

var rx = /[W].*/;
var text = "Hello World"
text.replace( rx, "$1" );

Upvotes: 0

Björn Roberg
Björn Roberg

Reputation: 2366

You need to escape the escaped RegExp sequences:

var foo2 = function (className) {
  return new RegExp("(?:^|\\s)" + className + "(?!\\S)", "g");
  //----------------------^^^---------------------^^^
};

Your original function would return:

foo("ASD")
// returns:
/(?:^|s)ASD(?!S)/g

but we're after this:

foo2("ASD")
// returns:
/(?:^|\s)ASD(?!\S)/g

Upvotes: 2

Related Questions