JS RegExp help with an expression

JS RegExp help with an expression


While doing the palindrome algorithm section, there is one part that I don’t understand which is:
str.replace(/[\W_]/g, ‘’).toLowerCase().
What I don’t understand from this is what is boldened.
I want to make sure that I am understanding this correctly.
" /[\W_]g,’’ "is telling the .replace() method to find any non-character (specifically the underscore ( _ )) and delete it with the second parameter of the method (’’)

Do I understand that correctly?

Thank you.


According to MDN:

\W: Matches any non-word character. Equivalent to [^A-Za-z0-9_].

For example, /\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “50%.”

So that would make the underscore unnecessary.

Anyway, replace() tries to find characters that match the first parameter and replaces it with the second parameter. In this case the second parameter is "", so you effectively delete everything that matches.

So, you understand it correctly :slightly_smiling_face:


Thanks for the help!