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 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.
<!DOCTYPE html> < html > < head > < title > JavaScript RegExp s Metacharacter </ title > </ head > < body style = "text-align:center" > < 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); alert("The new string is: \n" + str1); } </ script > </ body > </ html > |
Output:
Before Clicking the button:
After Clicking the button:
Example 2: This example replaces all the white spaces with hash(#).
<!DOCTYPE html> < html > < head > < title > JavaScript RegExp s Metacharacter </ title > </ head > < body style = "text-align:center" > < 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); alert("The new string is: \n" + str1); } </ script > </ body > </ html > |
Output:
Before Clicking the button:
After Clicking the button:
Supported Browsers: The browsers supported by RegExp \s Metacharacter are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer