JavaScript – Detect if a string contains any space

featured Image

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?

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *