How to use Array.prototype.some In Javascript
In this approach, we will create a function that uses the some method to iterate through each character in the string and check if it is a whitespace character.
Example: In this example, we will use the some method to check each character in the string.
function containsWhitespace(str) {
return [...str].some(char => char === ' ' || char === '\t' || char === '\n');
}
let str1 = "Hi I am a Geek";
let str2 = "w3wiki";
if (containsWhitespace(str1)) {
console.log("The string contains whitespace characters.");
} else {
console.log("The string does not contain whitespace characters.");
}
if (containsWhitespace(str2)) {
console.log("The string contains whitespace characters.");
} else {
console.log("The string does not contain whitespace characters.");
}
// Nikunj Sonigara
Output
The string contains whitespace characters. The string does not contain 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
Contact Us