Check if a string has white space in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To check whitespace in a string, use the concept of indexOf(‘ ’). Following is the code −

Example

function stringHasTheWhiteSpaceOrNot(value){
   return value.indexOf(' ') >= 0;
}
var whiteSpace=stringHasTheWhiteSpaceOrNot("MyNameis John");
   if(whiteSpace==true){
      console.log("The string has whitespace");
   } else {
      console.log("The string does not have whitespace");
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo108.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo108.js
The string has whitespace
raja
Published on 09-Sep-2020 12:58:53
Advertisements