1

Why doesn't this assign prepClass to the string selectorClass with underscores instead of non alpha chars? What do I need to change it to?

var regex = new RegExp("/W/", "g");
var prepClass = selectorClass.replace(regex, "_");

1 Answer 1

4

A couple of things:

  • If you use the RegExp constructor, you don't need the slashes, you are maybe confusing it with the syntax of RegExp literals.
  • You want match the \W character class.

The following will work:

var regex = new RegExp("\\W", "g");

The RegExp constructor accepts a string containing the pattern, note that you should double escape the slash, in order to get a single slash and a W ("\W") in the string.

Or you could simply use the literal notation:

var regex = /\W/g;

Recommended read:

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

3 Comments

Correctamundo. Thanks. I'll accept as soon as the time limit is up
Side question - can I just use /\W/g inside replace rather than defining a variable regex?
@Matrym: Yes, you can use either directly in the replace: .replace(new RegExp("\\W", "g"), "_") or .replace(/\W/g, "_").

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.