Open In App

JavaScript RegExp \s Metacharacter

Improve
Improve
Like Article
Like
Save
Share
Report

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 a dash.

Javascript




function geek() {
    let regex = /\s/g;
    let replace = "-";
    let str = "GeeksforGeeks is the computer "
        + "science\nportal\tfor geeks.";
    let str1 = str.replace(regex, replace);
    console.log("The new string is: \n" + str1);
}
geek()


Output

The new string is: 
GeeksforGeeks-is-the-computer-science-portal-for-geeks.

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

Javascript




function geek() {
    let regex = new RegExp("\\s", "g");
    let replace = "#";
    let str = "Geeks Classes is a Classroom "
        + "programme\nby GeeksforGeeks\tto"
        + " enhance DSA";
    let str1 = str.replace(regex, replace);
    console.log("The new string is: \n" + str1);
}
geek()


Output

The new string is: 
Geeks#Classes#is#a#Classroom#programme#by#GeeksforGeeks#to#enhance#DSA

Supported Browsers:

  • 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.  



Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads