JS RegExp help with an expression

JS RegExp help with an expression
0

#1

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.


#2

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:


#3

Thanks for the help!