-4
var newstr= str.replace(/[\W_]/g, '');    //replace all non-alfanumeric blank

This was the code i tried while removing the non-alfanumeric characters from a string in Javascript.

Please explain what is the difference between </[\W_]/g> and </\w+/g> and </\w/g>.

Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
spetsnaz
  • 31
  • 4

2 Answers2

1

If we have /[\W_]/g any of this special symbols in str object replace the empty("") value.

Thirumal Govindaraj
  • 351
  • 2
  • 4
  • 12
1

\w : 1 word character. It's equivalent to [A-Za-z0-9_]

\w+ : 1 or more word characters.

\W : 1 non-word character. It's equivalent to [^\w] or [^A-Za-z0-9_]
So \W is anything that's not a letter, not a digit and not an underscore.

[\W_] : A character class with non-word characters and underscore. It's equivalent to [^A-Za-z0-9]

Note that with a global replace to nothing, the code str.replace(/\W/g,'') will give the same result as str.replace(/\W+/g,''). The former will just replace them 1 character at a time, while the latter will replace groups of 1 or more characters at the time.

More info about the regex syntax can be found in this old post

Or you could just copy&paste your regex in an online regex tester.
For example regexr or regex101
Then check out the explain, or hover your mouse pointer over the pattern to get hints about each part of the pattern.

LukStorms
  • 19,080
  • 3
  • 26
  • 39