How to use regular expressions In Javascript
To determine whether a string contains whitespace characters we can make use of regular expressions. A regular expression (regex) is a sequence of characters that define a search pattern. The “\s” metacharacter is used to match the whitespace character.
Example: Below is the implementation of the approach
function checkWhitespace(str) {
return /\s/.test(str);
}
let str = "Hi I am a Geek";
if (checkWhitespace(str)) {
console.log(
"The string contains whitespace characters."
);
} else {
console.log(
"The string does not contain whitespace characters."
);
}
Output
The string contains whitespace characters.
JavaScript Program to Check if a String Contains any Whitespace Characters
In this article, we are given a string str, you need to find whether the given string contains whitespace characters or not in JavaScript. Whitespaces can occur at any position whether at the beginning or in between or at the end of the string.
Example 1:
Input:
str = Hi I am a Geek
Output:
The string contains whitespace characters
Explanation:
In the input string "Hi I am a geek" there are 4 whitespace characters which is shown by "_" :
Hi_I_am_a_Geek
So we return "The string contains whitespace characters"
Example 2:
Input:
str = helloWorld
Output:
The string does not contains whitespace characters
Here are some common approaches:
Table of Content
- Using regular expressions
- Using JavaScript Sets
- Using for loop
- Using String.prototype.includes
- Using Array.prototype.some