JavaScript RegExp – \s

JavaScript RegExp – \s

JavaScript provides the RegExp object to work with regular expressions, which are patterns used to match character combinations in strings. One of the common metacharacters used in regular expressions is \s, which matches any whitespace character, including spaces, tabs, and line breaks. This article will explore the usage of \s in JavaScript regular expressions with examples.

The syntax of \s

To use \s in a regular expression in JavaScript, you can simply include it in between two forward slashes(/…/). Here’s the syntax:

var regexp = /pattern\s/;

In the above syntax, ‘pattern’ refers to the regular expression pattern to match, followed by the \s metacharacter.

Examples of using \s

Now, let’s see some examples of using \s in JavaScript regular expressions with sample code.

Example 1: Matching a whitespace character

To match a whitespace character, you can use the \s metacharacter in your regular expression. Here’s an example:

var text = "Hello World";
var regexp = /\s/;

console.log(regexp.test(text));    // true

In the above example, the regular expression is / \s /, which matches any whitespace character. The test() method returns boolean true because the whitespace character is present in the ‘Hello World’ string.

Example 2: Matching multiple whitespace characters

To match multiple whitespace characters, you can use the \s+ metacharacter in your regular expression. Here’s an example:

var text = "Javascript  Regular  Expressions";
var regexp = /\s+/;

console.log(text.split(regexp));   // ["Javascript", "Regular", "Expressions"]

In the above example, the regular expression is / \s+ /, which matches one or more whitespace characters. The split() method is used to split the string based on the regular expression, resulting in an array of three strings: “Javascript”, “Regular”, and “Expressions”.

Example 3: Matching whitespace characters at the beginning or end of a string

To match whitespace characters only at the beginning or end of a string, you can use the ^ or $ anchor character in your regular expression. Here’s an example:

var text = "    Hello World   ";
var regexp = /^\s+|\s+$/g;

console.log(text.replace(regexp, ""));   // "Hello World"

In the above example, the regular expression is / ^\s+|\s+/g, which matches one or more whitespace characters at the beginning (^) or end () of a string. The replace() method is used to remove the whitespace characters from the string, resulting in “Hello World”.

Conclusion

In summary, the \s metacharacter in JavaScript regular expressions is used to match any whitespace character, including spaces, tabs, and line breaks. We explored several examples of using \s in regular expressions, which can help you manipulate strings more efficiently.

Like(0)