JavaScript \s or \S Metacharacters | RegEx for WhiteSpace

This post is published to provide information about two metacharacters used in JavaScript regular expressions. That are:

The \s metacharacter in JavaScript

The \s metacharacter is used when we need to match any whitespace available in the specified text using a regular expression. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "I got 100% marks in Cyber Security!";
      let pattern = /\s/g;
      document.getElementById("xyz").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

There are five commas, indicating six whitespaces. One before the first comma and one after the last comma. Whereas other whitespaces are in-between the commas.

Note: A space, tab, vertical tab, new line, carriage return, and form feed are all in the category of whitespaces here.

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

The \S metacharacter in JavaScript

Unlike \s, the \S metacharacter is used when we need to match all characters other than whitespace characters. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "I got 100% marks in Cyber Security!";
      let pattern = /\S/g;
      document.getElementById("xyz").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!