我看到了這個線程 ,可是沒有看到JavaScript特定的示例。 是否有一個簡單的string.Empty
在JavaScript中可用,仍是僅檢查""
一種狀況? html
忽略空格字符串,您可使用它來檢查null,empty和undefined: web
var obj = {}; (!!obj.str) //returns false obj.str = ""; (!!obj.str) //returns false obj.str = null; (!!obj.str) //returns false
簡潔,它適用於未定義的屬性,儘管它不是最易讀的。 測試
我沒有注意到一個考慮到字符串中可能存在空字符的答案。 例如,若是咱們有一個空字符串: this
var y = "\0"; // an empty string, but has a null character (y === "") // false, testing against an empty string does not work (y.length === 0) // false (y) // true, this is also not expected (y.match(/^[\s]*$/)) // false, again not wanted
要測試其無效性,能夠執行如下操做: spa
String.prototype.isNull = function(){ return Boolean(this.match(/^[\0]*$/)); } ... "\0".isNull() // true
它適用於空字符串和空字符串,而且全部字符串都可訪問。 另外,它能夠擴展爲包含其餘JavaScript空字符或空格字符(即,不間斷空格,字節順序標記,行/段落分隔符等)。 prototype
嘗試: 線程
if (str && str.trim().length) { //... }
若是您只想檢查是否有任何價值,能夠 code
if (strValue) { //do something }
若是您須要專門檢查是否有一個空字符串,而不是null,那麼我認爲使用===
運算符來檢查""
是最好的選擇(這樣您就能夠知道它其實是您要與之進行比較的字符串) )。 htm
if (strValue === "") { //... }
我不會太擔憂最有效的方法。 使用最清楚您意圖的內容。 對我來講,一般是strVar == ""
。 ip
編輯:來自康斯坦丁的評論,若是strVar可能最終包含一個整數0值,那麼那確實是那些意圖明確的狀況之一。