只有空格串在我的代碼,我需要寫一個,如果其他塊級如何檢查其在JavaScript
when the variable `currentValue` is holding only spaces -> certain code
但我不知道如何寫這個條件爲currentValue
可以串任何尺寸。它可以容納" "
," "
等 如果我寫currentValue!=" "
它檢查單個空間。
只有空格串在我的代碼,我需要寫一個,如果其他塊級如何檢查其在JavaScript
when the variable `currentValue` is holding only spaces -> certain code
但我不知道如何寫這個條件爲currentValue
可以串任何尺寸。它可以容納" "
," "
等 如果我寫currentValue!=" "
它檢查單個空間。
可能看起來像
if(!currentValue.trim().length) {
// only white-spaces
}
文檔:trim
即使它非常不言自明的; 字符串參考currentValue
得到修剪,這基本上意味着在開始和結束的所有空白字符將被刪除。如果整個字符串由空格字符組成,則會將其全部清除,這意味着length
的結果爲0
,而!0
將爲true
。
約性能,我比較了這個解決方案與RegExp來自@mishik的方式。事實證明,.trim()
在FireFox中快得多,而RegExp
在Chrome中似乎更快。
簡單:
if (/^\s*$/.test(your_string)) {
// Only spaces
}
要匹配space
只:
if (/^ *$/.test(your_string)) {
// Only spaces
}
說明:/^\s*$/
- 匹配字符串的開頭,然後任意數量的空格(空格,換行,標籤等..),然後結束字符串。 /^ *$/
- 相同,但僅適用於空格。
如果您不想匹配空字符串:將*
替換爲+
以確保至少存在一個字符。
試戴:
your_string.split(" ").length
編輯:
var your_string = " ";
var x = your_string.split(" ").length - 1;
if (your_string.length > 0 && (your_string.length - x) == 0) {
alert("your_string has only spaces");
}
你的意思是空間(炭32)準確,或任何空白(行結束,標籤等) ? – georg
你應該嘗試使用谷歌搜索的東西,如'JavaScript匹配字符串'。 – 1983