JavaScript – Detect if a string contains any space

In this post, we will see how to detect any whitespace in a string.

To detect if a string has any space in it, we can use the regex test() method or the String indexOf() method in Javascript.

Let’s see some examples.

Using RegExp.test() to detect whitespace in a String

We can use the regex test() method on a given string to detect if the given string contains any spaces in it.

The test() method will return true, if the expression is matched in the string otherwise it will return false.

function checkSpaces(str){
    return /s/.test(str)
}

console.log(checkSpace('Hello World')) // true
console.log(checkSpace('hello_world')) // false

In the above example, we have called the test method on the regular expression /s/.

The forward slash (/ /) define the start and end of the regular expression.

And the regex character /s matches any whitespace characters in a string like space and tab.

Read More RegExp.prototype.test() – JavaScript | MDN

Using indexOf() to check for whitespace in String

We can also use the String indexOf() method to check for whitespace in a given string.

The indexOf returns the position of the first occurrence of a given value in a string. If the value is not found it returns -1.

Now here the value we will search in a given string is an empty space (' ') with indexOf method.

function detectSpaces(str){
    if (str.indexOf(' ') !== -1){
      return true;
    }
    return false
}

console.log(detectSpaces('Hello World')) //true
console.log(detectSpaces('hello_world')) //false

In this example, the function returns true if the string contains any white space in it else it returns false

Conclusion: So to detect any white space in a given string in Javascript we can use the regex test() method or the stringindexOf() method.


Related Topics:

How to check if String contains only spaces in JavaScript

5 ways to convert string to number in JavaScript

Replace all occurrences of a string in JavaScript

Create multiline string in JavaScript | Split string to Multilines

How to create a Multiline string in JavaScript?

Scroll to Top