2012-04-21 145 views
27

其中包含一個空格的字符串長度總是等於1:檢測字符串只包含空格

alert('My str length: ' + str.length); 

的空間是一個字符,所以:

str = " "; 
alert('My str length:' + str.length); // My str length: 3 

我怎樣才能做一個區分在一個空字符串和一個只包含空格的字符串之間?如何檢測只包含空格的字符串?

+0

修剪它並檢查長度爲零。你在使用jQuery嗎? – 2012-04-21 18:58:26

+2

刪除所有空格並查看字符串長度是否爲「0」?或者使用正則表達式來匹配只有空白字符串... – 2012-04-21 18:58:35

+1

可能的重複[如何檢查輸入文本字段是否只包含空白?](http://stackoverflow.com/questions/2662245/how-to-check -whether-the-input-text-field-contained-only-white-spaces) – 2012-04-21 18:59:23

回答

47

要達到此目的,您可以使用正則表達式來刪除字符串中的所有空白。如果結果字符串的長度爲0,那麼您可以確定原始文件只包含空格。試試這個:

var str = " "; 
if (!str.replace(/\s/g, '').length) { 
    // string only contained whitespace (ie. spaces, tabs or line breaks) 
} 

Example fiddle

+0

那麼,字符串只包含空格。 – dwerner 2012-04-21 19:03:34

4

你可以爲你的字符串創建一個微調功能修剪您的字符串值。

String.prototype.trim = function() { 
    return this.replace(/^\s*/, "").replace(/\s*$/, ""); 
} 

現在將可以爲您的每一個字符串,你可以使用它作爲

str.trim().length// Result will be 0 

您也可以使用此方法在字符串即

的開始和結束時刪除空格
" hello ".trim(); // Result will be "hello" 
+2

擴展內置對象的原型是一個壞主意。 – sbichenko 2015-06-21 15:41:01

+0

@exizt:如果它只會被他自己的代碼使用,該怎麼辦? – Shehzad 2015-06-27 10:17:57

9

最快的解決方案是使用正則表達式原型函數test()並尋找任何不是空格或換行符的字符\S

if (/\S/.test(str)) 
{ 
    // found something other than a space or line break 
} 

如果你有超長的字符串,它可以產生顯着的差異。

相關問題