JavaScript Check if String Contains Spaces

JavaScript Check if String Contains Spaces | The string Object in JavaScript is used to represent and manipulate a series of characters. They are mainly used to hold data which is in text form. This article focuses on how one can check whether a string contains spaces in it.

JavaScript Check if String Contains Spaces Using Regular Expressions

The JavaScript regular expression contains a method called test(). It searches for a match between a regular expression and a specified string. This approach can be used to find if a string contains spaces in it.

function checkSpaces(string) {
    return /\s/.test(string)
}
console.log(checkSpaces(" "))
console.log(checkSpaces("Hello World"))
console.log(checkSpaces("hi"))
console.log(checkSpaces(""))

Output:-

true
true
false
false

In the above example, a function is created which can be used to check for spaces.  The .test() method returns true if it can find the regular expression in the given string. The / symbol represents the start and end of a regular expression. The /s character matches a single space. 

The same function can be modified a bit to check if a string contains only spaces in the following way:-

function checkSpaces(string) {
    return /^\s*$/.test(string);
}
console.log(checkSpaces(" "))
console.log(checkSpaces("Hello World"))
console.log(checkSpaces("hi"))
console.log(checkSpaces(""))

Output:-

true
false
false
true

The ^ symbol checks for the starting point of a string. The * symbol checks for the previous item 0 or more times. The $ symbol checks for the end of the string.

JavaScript Check if String Contains Spaces Using indexOf

The indexOf method of the String Object can be used to check if a string contains spaces. 

function checkSpaces (string) {
	if(string.indexOf(' ') !== -1)
		return true
	else
		return false
}

console.log(checkSpaces(" "))
console.log(checkSpaces("Hello World"))
console.log(checkSpaces("hi"))
console.log(checkSpaces(""))

Output:-

true
true
false
false

The indexOf method returns the index of the value passed to it through an argument. If it is not able to find that value, it returns -1. This along with an if conditional is used in the above example.

Thus we studied how we can check for spaces in a string by using two methods. You can use any one of them in your code. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.