在 JavaScript 中检查字符串是否有空格?

javascriptweb developmentobject oriented programming更新于 2025/11/13 22:36:17

要检查字符串中的空格,请使用 indexOf(‘ ’) 的概念。以下是代码 −

示例

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");
}

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo108.js。

输出

这将产生以下输出 −

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

相关文章


有用资源