Check If A String Contains Whitespace In JavaScript

To check if a string contains whitespace in JavaScript, you can use two methods –

  1. Use test() with a regular expression – /\s/
  2. Use indexOf() with a space character

Let’s have a look at both the methods:

Check If A String Contains Whitespace In JavaScript

check if a string contains whitespace in javascript

Method 1: Use test() With A Regular Expression /\s/

The JavaScript test() method is used to check whether or not a string contains a specified pattern.

If the specified pattern is found, then the test() method returns true otherwise it returns false.

We can use the regular expression /\s/ to check if a string contains at least one whitespace.

Example

var str = "Hello world!";

var result =/\s/.test(str);

console.log(result); //true

You can write a reusable function to check if a string contains whitespace or not.

Example

function hasWhitespace(s) {

  return /\s/.test(s);

}

console.log(hasWhitespace("Hello world!")); //true

console.log(hasWhitespace("Hello")); //false

Note that this method checks for all whitespaces including tabs, new lines, etc.

For example,

console.log(hasWhitespace("Hello\nworld!")) //will also return true.

If you want to check for only spaces, then use the second method.

Method 2: Use indexOf() With A Space Character

The JavaScript indexOf() method is used to check whether a specified value exists in a string or not.

It returns the index of the first occurrence of a specified value.

If the specified value is not found, it returns -1.

We can use a space character as the specified value to check if there are any spaces in a string.

Example

var str = "Hello world!";

var result = str.indexOf(" ");

console.log(result); //6

You can write a reusable function to check if a string contains whitespace or not.

The indexOf() method will return -1 if there is no whitespace in the string.

Example

function hasWhitespace(s) {

  return s.indexOf(‘ ‘) >= 0;

}

console.log(hasWhitespace("Hello world!")); //true

console.log(hasWhitespace("Hello")); //false

Note that this method doesn’t check for all whitespaces.

For example, console.log(hasWhitespace(“Hello\nworld!”)) will return false.

If you want to check for all whitespaces, then use the first method.

These are the two methods that you can use to check if a string contains whitespace in JavaScript.

You can choose any one of these methods based on your requirements.

I hope this helped you. 🙂

Leave a Reply