JavaScript RegExp s Metacharacter (original) (raw)

Last Updated : 06 Dec, 2024

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.