0

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

2
  • 1
    You'd better use classList property if you are not obliged to support old browers. Property is IE10+. Commented Sep 4, 2013 at 13:22
  • old browsers I must support... otherwise you are correct! Commented Sep 4, 2013 at 13:38

2 Answers 2

2

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

Comments

0

Simple:

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

Comments

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.