JavaScript RegExp \s Metacharacter
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 = "w3wiki is the computer " + "science\nportal\tfor Beginner." ; let str1 = str.replace(regex, replace); console.log( "The new string is: \n" + str1); } geek() |
Output
The new string is: w3wiki-is-the-computer-science-portal-for-Beginner.
Example 2: This example replaces all the white spaces with hash(#).
Javascript
function geek() { let regex = new RegExp( "\\s" , "g" ); let replace = "#" ; let str = "Beginner Classes is a Classroom " + "programme\nby w3wiki\tto" + " enhance DSA" ; let str1 = str.replace(regex, replace); console.log( "The new string is: \n" + str1); } geek() |
Output
The new string is: Beginner#Classes#is#a#Classroom#programme#by#w3wiki#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.
Contact Us