Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript RegExp \s Metacharacter

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 06 Jan, 2023
Improve Article
Save Article

The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is the same as [ \t\n\r].
Syntax:  

/\s/ 

or 

new RegExp("\\s")

Syntax with modifiers: 

/\s/g 

or  

new RegExp("\\s", "g")

Example 1: This example replaces the white spaces with dash.

html




<h1 style="color:green">
    GeeksforGeeks
</h1>
  
<h2>RegExp \s Metacharacter</h2>
  
  
<p>
    Input String: GeeksforGeeks is the computer
    science\nportal\tfor geeks.
</p>
  
  
<button onclick="geek()">
    Click it!
</button>
  
<p id="app"></p>
  
  
<script>
    function geek() {
        var regex = /\s/g;
        var replace = "-";
        var str = "GeeksforGeeks is the computer "
                + "science\nportal\tfor geeks.";
        var str1 = str.replace(regex, replace);
        document.getElementById("app")
                  .innerHTML ="The new string is: \n" + str1;
    }
</script>

Output: 

 RegExp \s Metacharacter

 RegExp \s Metacharacter

Example 2: This example replaces all the white spaces with hash(#).
 

html




<h1 style="color:green">
    GeeksforGeeks
</h1>
  
<h2>RegExp \s Metacharacter</h2>
  
  
<p>
    Input String: Geeks Classes is a Classroom
    programme by GeeksforGeeks to enhance DSA.
</p>
  
  
<button onclick="geek()">
    Click it!
</button>
  
<p id="app"></p>
  
  
<script>
    function geek() {
        var regex = new RegExp("\\s", "g");
        var replace = "#";
        var str = "Geeks Classes is a Classroom "
                + "programme\nby GeeksforGeeks\tto"
                + " enhance DSA";
        var str1 = str.replace(regex, replace);
        document.getElementById("app").innerHTML = "The new string is: \n" + str1;
    }
</script>

Output:

 RegExp \s Metacharacter

 RegExp \s Metacharacter

Supported Browsers: The browsers supported by RegExp \s Metacharacter are listed below.
 

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Internet Explorer

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Complete Reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!