JavaScript \s or \S Metacharacters | RegEx for WhiteSpace

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

The \s Metacharacter

The \s metacharacter is used when we need to match any whitespaces available in the specified text using 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 to 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 comes in the category of whitespaces here.

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

The \S Metacharacter

Unlike \s, the \S metacharacter is used when we need to match with 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 »



Like/Share Us on Facebook 😋