A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-regexp-s-metacharacter/ below:

JavaScript RegExp \s Metacharacter - GeeksforGeeks

JavaScript RegExp \s Metacharacter

Last Updated : 11 Jul, 2025

The \s metacharacter in JavaScript regular expressions matches any whitespace character. This includes spaces, tabs, form feeds, line breaks, and other whitespace characters as defined in Unicode.

JavaScript
let regex = /\s/;
let str1 = "Hello World";
let str2 = "HelloWorld";
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 
Syntax:
/\s/
Key Points Real-World Examples 1. Detecting Whitespace JavaScript
let regex = /\s/;
let str = "Find whitespace in this string.";
console.log(regex.test(str)); 

The \s metacharacter detects the presence of any whitespace character.

2. Splitting by Whitespace JavaScript
let str = "Split this text by spaces, tabs, or line breaks.";
let regex = /\s+/;
console.log(str.split(regex));

Output
[
  'Split',   'this',
  'text',    'by',
  'spaces,', 'tabs,',
  'or',      'line',
  'breaks.'
]

The \s+ pattern splits the string into parts, treating multiple consecutive whitespace characters as a single separator.

3. Removing Extra Whitespace JavaScript
let str = "   Remove   extra   spaces   ";
let regex = /\s+/g;
console.log(str.trim().replace(regex, " ")); 

Output
Remove extra spaces

Here, \s+ matches one or more consecutive whitespace characters, which are replaced by a single space.

4. Validating Input Without Whitespace JavaScript
let regex = /\s/;
let username = "NoSpacesAllowed";

if (regex.test(username)) {
    console.log("Invalid username. It contains spaces.");
} else {
    console.log("Valid username.");
}

The \s metacharacter is useful for ensuring inputs like usernames or passwords do not contain spaces.

5. Matching Whitespace in Multiline Text JavaScript
let regex = /\s/g;
let text = "Line 1\nLine 2\tTabbed";
console.log(text.match(regex)); 

Output
[ ' ', '\n', ' ', '\t' ]

The \s metacharacter detects all whitespace characters, including line breaks and tabs, in the text.

Why Use the \s Metacharacter? Conclusion

The \s metacharacter is a versatile tool for working with spaces and other whitespace characters, making it essential for string manipulation and validation in JavaScript.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4