Regular Expression Question

Regular Expression Question
0.0 0


Is there a reason why the regular expression below does not catch the underscore character?

function palindrome(str) {
var output = str.replace(/\W/g, “”).toLowerCase();
var output2 = output.split("").reverse().join("");

if(str == output2) {
return true;
return false;


Output is false.
If I console.log() I see the underscore remains in the string.
I though /w and /W would catch all non-alphanumeric characters including the _ ?
(I actually googled this and this is a copy paste of the code I found. Seems to work for them but not for me?)

I also tried the regular expression /\W_/g but then I get an error message about a missing ;

Thanks for any help you can provide.


The \W metacharacter is used to find a non-word character. In JavaScript regular expressions, the underscore character is considered a word character, so that is why it is not replacing it with a blank string.



The documentation for RegExp says \W is equivalent to [^A-Za-z0-9_].
I am almost afraid to ask, but does the underscore in that expression do?


It just means the underscore character. The ^ character is special in that it means NOT anything inside the [ ]. So, [^A-Za-z0-9_] means every character that is not A-Z, or a-z, 0-9, or _


Ok, so it is excluding the underscore. I think, lol.

Ok, I have gotten a pass in the palindrome exercise, but I did it in a hideous fashion using .split() with a underscore delimiter.

Is there a way to add to a regular expression? I can’t seem to find anything that makes sense on this. Many of the results I am finding are using bracket notation and characters I do not see covered in a search for “Javascript Regular Expression Tutorial”.


To replace all characters that are non-word character or the underscore character, you could write:

str.replace(/\W_/g, '')


Argh, I swear I tried that and it flagged the line as having a missing semicolon or something.

Thank you again for the help Randell.