In JavaScript, you can use regular expressions (regex) to work with space characters. The space character itself can be represented in regex using the \s
metacharacter. Here’s the syntax for using the space character in regex:
Using the RegExp
constructor:
const regex = new RegExp("\\s");
Note: In the RegExp
constructor, the backslash \
needs to be escaped with another backslash \\
because backslashes are escaped characters in strings.
Using the regex literal syntax:
const regex = /\s/;
In the regex literal syntax, you don’t need to escape the backslash.
Both syntaxes create a regular expression that matches a single space character. If you want to match multiple consecutive space characters, you can use the \s+
pattern:
const regex = /\s+/;
In this case, the regular expression matches one or more consecutive space characters.
JavaScript regex space character example
Simple example code that demonstrates the usage of regular expressions to match and replace space characters in JavaScript:
// Example 1: Matching space characters
const regex1 = /\s/;
const hasSpace = regex1.test("Hello World");
console.log(hasSpace);
// Example 2: Replacing space characters
const str1 = "Hello World";
const regex2 = /\s/g;
const replaced = str1.replace(regex2, "-");
console.log(replaced);
// Example 3: Splitting a string by space characters
const str2 = "Hello World";
const regex3 = /\s+/;
const parts = str2.split(regex3);
console.log(parts);
Output:
Matching multiple consecutive space characters:
const regex = /\s+/;
const hasMultipleSpaces = regex.test("Hello World"); // true
Comment if you have any doubts or suggestions on this Js Regex topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version