Check if a string has white space in JavaScript?

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


function stringHasTheWhiteSpaceOrNot(value){
   return value.indexOf(' ') >= 0;
var whiteSpace=stringHasTheWhiteSpaceOrNot("MyNameis John");
      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.


This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo108.js
The string has whitespace