In regular expressions (regex), the \s
character class matches any whitespace character, including spaces, tabs, and newlines.
Here’s an example of how you can use the \s
character class to match spaces in JavaScript:
let regex = /\s/;
let str = "Hello World";
let result = str.match(regex);
console.log(result);
This code defines a regular expression regex
that matches any whitespace character, and then uses the match
method to search for a match in the string str
. The result of the match
method will be an array containing the matched spaces, or null
if no match was found.
If you want to match multiple spaces, you can use the +
operator, which matches one or more occurrences of the preceding pattern:
let regex = /\s+/;
let str = "Hello World";
let result = str.match(regex);
console.log(result);
This code defines a regular expression that matches one or more whitespace characters, and then uses the match
method to search for matches in the string str
. The result of the match
method will be an array containing the matched sequences of spaces, or null
if no match was found.
+ There are no comments
Add yours