In this solution, I can’t figure out why the brackets or the underscore are included in the Regex. I have looked aat MDN and W3schools and couldn’t find what they do.
It would be nice if you were more specific. Let’s look at the line:
In that, you are performing a regex on the variable str. It is looking for any whitespace or underscores (
[\W_]) anywgere (
g) and replacing it with nothing (
''). Replacing it with nothing means that you are removing it. Why the brackets? Because (afaik) if you just did
str.replace(/\W_/g, ''), it would specifically look for whitespace char followed by underscores. It wouldn’t catch multiple spaces in a row, for example. The brackets tell it this is a list of things to look for, not this specific combination and order. Why underscores? That’s not a specific regex thing, that’s actually one of the things we are looking for to remove. Underscores are sometimes used as in strings as a fake space. Why does this solution not look for other non-alphanumeric chars? I don’t know. But this is what they have.
When confused about regex, I’d recommend looking at sites like regex101.com. It’s a great place to try things out and see what is caught and what isn’t.
It dosent help right now, but I didn’t really get it at all until I got this book that has a great diagram on regex special characters. It really is a great buy.