Check if a String has White Space in JavaScript

To check if a string has white space or not, you can use the built-in String.includes() method. The includes() method takes the search string as a parameter and checks if it is present in the given string or not.

If the search string is present in the given string, the includes() method returns true, otherwise, it returns false.

In our case, the search string is a white space i.e. " " or ' ' and we have to search for it in the given string using the includes() method.

See the following example:

const str1 = "Hello World";

console.log(str1.includes(" "));
// Output: true


const str2 = "HelloWorld";

console.log(str2.includes(" "));
// Output: false

In the above example, the first string contains a white space after “Hello”, therefore, the includes() method returns true. Whereas the second string does not contain any white space, therefore, the includes() method returns false.


The includes() method does also take a second optional parameter which specifies the position in the string from where the search should happen. Its default value is 0.

Have a look at the following example:

const str = "Hello World";

console.log(str.includes(" ", 6));
// Output: false

console.log(str.includes(" ", 4));
// Output: true

Method 2: Use the String.indexOf() Method

Another way to check if the string contains white space or not is to use the built-in String.indexOf() method.

The indexOf() method takes in a single parameter which is the search string and searches for it in the entire string. If the search string is present in the given string, it returns the index of its first occurrence, otherwise, it returns -1.

See the following example:

const str1 = "Hello World";

console.log(str1.indexOf(" "));
// Output: 5


const str2 = "HelloWorld";

console.log(str2.indexOf(" "));
// Output: -1

Just like the includes() method, the indexOf() method does also take a second optional parameter, which is the position in the string from where the search should happen. Its default value is 0.

const str = "Hello there";

console.log(str.indexOf(" ", 3));
// Output: 5

console.log(str.indexOf(" ", 6));
// Output: -1

Please keep in mind that the indexOf() method returns only the index of the first occurrence of the search string. It means, If the search string is present at multiple places, it will return the index of its first occurrence only.

Have a look at the following example:

const str = "It contains multiple spaces";

console.log(str.indexOf(" "));
// Output: 2

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.