In this article, we will be seeing multiple approaches to see if the string contains spaces in javascript.
We will discuss the following in detail –
- Check if string contains spaces in javascript using the string indexOf method
- Check the count of all whitespace in the string
- Â Check if string contains spaces in javascript using regex (regular expression)
- Check if the string is an empty stringÂ
- Check if the string contains only whitespaces
Solution 1: using indexOf method
String.prototype.indexOf method is available on each string object.
It takes one argument i.e the substring to search for and searches in the entire string and returns the index of the first occurrence of the substring.
If the substring is not present then it returns -1
const text = 'This is awesome stuff';
const searchText = ' ';
console.log(text.indexOf(searchText)); // output: 4
console.log(text.indexOf('awesome')); // output: 8
From the above code, we can easily see if the indexOf method returns a non-negative number for substring ‘Â ‘Â then the string has the whitespace.
Let me write a javascript function that can be called to check if the string has whitespace or not.
function isStringContainSpace(str) {
return str.indexOf(' ');
}
console.log(isStringContainSpace('This is awesome stuff'));
// output: 4
HW: Check the count of all whitespaces in the string?
function countAllSpace(str) {
}
console.log(countAllSpace('This is awesome stuff'));
// output: 3
Above is the function declaration for the HW problem, please fill in the implementation for it.
Although I have added the solution at the end of the article I would request you to give it a try and only check the solution if you are exhausted or verifying the solution.Â
Solution 2: using regex
Let’s see how can we check if the string contains whitespace using regex.
function isStringContainSpace(str) {
const regex = /\s+/g;
return str.match(regex) !== null;
}
console.log(isStringContainSpace('This is awesome stuff'));
// output: [" ", " ", " "]
console.log(isStringContainSpace('This'));
// output: null
String.prototype.match method returns an array if a match is found and null if there is no match.
In the first console.log, the input was “This is awesome stuff” which has 3 whitespaces, so str.match will return an array [” “, ” “, ” “] having 3 entries of whitespace. So the check str.match(regex) !== null will become true and hence the answer.
In the second console.log, the input “This” has no whitespace in it. So, the str.match will return the null. Hence, the check in the return statement is computed to false which will be returned as the answer.
Bonus Problem
Q.Check if string is an empty string or contains only whitespaces
To solve the above problem we will use String.prototype.trim method.
The trim method deletes the whitespace from the beginning and end of the string (and not in the middle). If the string is only made up of whitespace then after trim, only an empty string will be left.
function isEmptyString(str) {
return str.trim() === '';
}
console.log(isEmptyString('')); // true
console.log(isEmptyString(' ')); // true
console.log(isEmptyString('this is not empty')); // false
Q. Check the count of all whitespaces in the string?
function countAllSpace(str) {
const position = [];
let idx = str.indexOf(' ');
while (idx !== -1) {
position.push(idx);
idx = str.indexOf(' ', idx + 1);
}
return position.length;
}
console.log(countAllSpace('This is awesome stuff'));
// output: 3
console.log(countAllSpace(' '));
// output: 2
console.log(countAllSpace('This'));
// output: 0
In the function countAllSpace, we have kept a position array that stores the indices of all spaces found in the string.
The variable idx is initialized with the first index of the whitespace. And pushed this into the position array and check again for the next position of the whitespace till there are no whitespaces present.
The function returns the count of all spaces, however, if we wanted to print all the indices of whitespaces we could have returned the position array itself instead of its length.
I would strongly suggest you make this function more generic which takes the string and a substring and return all the occurrence of the substring.
That’s it for this article, I hope you have understood the content in detail.
If you like to read another article on javascript, you may read the following articles
Please share the articles on –
The latest tips and news from the industry straight to your inbox!
Join 30,000+ subscribers for exclusive access to our monthly news and tutorials!