Notice the case, that is, the first \w contains w which is in lowercase. Whereas the second \W contains W, which is in uppercase.
The \w Metacharacter
The \w metacharacter is used when we need to match all word characters.
Now the question is, what does it mean by word characters?
The answer to this question is: Any alphanumeric including _ (underscore) characters are word characters. That is, a-z, A-Z, 0-9, and _ are all word characters.
Here is an example demonstrating the \w metacharacter:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let myString = "Hey, I got 100% marks in Mathematics!"; let pattern = /\w/gi; document.getElementById("xyz").innerHTML = myString.match(pattern); </script> </body> </html>
All non-word characters such as comma (,), span, percentile (%), and exclamation mark (!) are excluded in the output.
Note: The match() method is used to match a string with/using a regular expression.
The \W Metacharacter
Unlike \w, the \W metacharacter is used when we need to match all characters except word characters. For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let mystr = "That's Good!"; let ptrn = /\W/gi; document.getElementById("xyz").innerHTML = mystr.match(ptrn); </script> </body> </html>
« Previous Tutorial Next Tutorial »
Like/Share Us on Facebook 😋