Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if a string has white space in JavaScript?
To check if a string contains whitespace in JavaScript, you can use several methods. The most common approaches are indexOf(), includes(), and regular expressions.
Using indexOf() Method
The indexOf() method returns the index of the first whitespace character, or -1 if none is found:
function stringHasTheWhiteSpaceOrNot(value){
return value.indexOf(' ') >= 0;
}
var whiteSpace = stringHasTheWhiteSpaceOrNot("MyNameis John");
if(whiteSpace == true){
console.log("The string has whitespace");
} else {
console.log("The string does not have whitespace");
}
// Test with different strings
console.log(stringHasTheWhiteSpaceOrNot("HelloWorld")); // false
console.log(stringHasTheWhiteSpaceOrNot("Hello World")); // true
The string has whitespace false true
Using includes() Method (Modern Approach)
The includes() method is more readable and returns a boolean directly:
function hasWhitespace(str) {
return str.includes(' ');
}
console.log(hasWhitespace("JavaScript")); // false
console.log(hasWhitespace("Java Script")); // true
console.log(hasWhitespace("Hello World!")); // true
false true true
Using Regular Expression
Regular expressions can detect any type of whitespace character (spaces, tabs, newlines):
function hasAnyWhitespace(str) {
return /\s/.test(str);
}
console.log(hasAnyWhitespace("NoSpaces")); // false
console.log(hasAnyWhitespace("Has Spaces")); // true
console.log(hasAnyWhitespace("Has\tTab")); // true
console.log(hasAnyWhitespace("Has\nNewline")); // true
false true true true
Comparison
| Method | Detects | Performance | Readability |
|---|---|---|---|
indexOf(' ') |
Only spaces | Fast | Good |
includes(' ') |
Only spaces | Fast | Excellent |
/\s/.test() |
All whitespace | Moderate | Good |
Conclusion
Use includes(' ') for checking spaces specifically, or /\s/.test() for detecting any whitespace character. The includes() method is the most readable for modern JavaScript applications.
Advertisements
