Regular Expression Question

Regular Expression Question
0.0 0

#1

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;
}

palindrome(“Race_cAr”);

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.


#2

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.


#3

Hmm.

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?


#4

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 _


#5

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


#6

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

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

#7

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.