JavaScript \w and \W Metacharacters: What are w and W in RegEx?

This post is published to define the two metacharacters that are used while working with JavaScript regular expressions. That are:

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 in JavaScript

The \w metacharacter is used when we need to match all word characters.

Now the question is, What does it mean by characters?
The answer to this question is: Any alphanumeric characters, 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:

HTML with JavaScript Code
<!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>
Output

All non-word characters such as commas (,), spans, percentiles (%), and exclamation marks (!) are excluded from the output.

Note: The match() method is used to match a string with or using a regular expression.

The \W metacharacter in JavaScript

Unlike \w, the \W metacharacter is used when we need to match all characters except word characters. For example:

HTML with JavaScript Code
<!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>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!