在 JavaScript 中檢查字串是否包含空白字元?


要檢查字串中是否有空白字元,請使用 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

更新於: 09-Sep-2020

4K+ 瀏覽量

開啟你的職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.