2013-07-25 52 views
4

我們可以.present?檢查一個字符串是不可─nil,且含有多於空白或空字符串以外的東西:在Rails使得Rails的`現在相當於'在Javascript

"".present?  # => false 
"  ".present? # => false 
nil.present?  # => false 
"hello".present? # => true 

我會像JavaScript中的類似功能,而不必爲它編寫功能,就像function string_present?(str) { ... }

這是我可以用Javascript開箱即可或通過添加到String的原型?

我這樣做:

String.prototype.present = function() 
{ 
    if(this.length > 0) { 
     return this; 
    } 
    return null; 
} 

不過,我將如何使這項工作:

var x = null; x.present 

var y; y.present 
+2

如果你沒有足夠的「也可能是唯一的空白」的要求,那麼你可以簡單地使用字符串變量在任何布爾語句中(例如'if(myStr){...}'),因爲'null','undefined'和''''是JavaScript中的錯誤值。 – ajp15243

+1

經過進一步的思考,我認爲你不會像'.present?'那樣獲得「好看」的東西,因爲你不能在JavaScript中使用'null.property'。 BradM可能是最好的解決方案。 – ajp15243

+0

看看[如何檢查字符串是否包含字符和空白,而不僅僅是空白?](http://stackoverflow.com/questions/2031085/how-can-i-check-if-string-contains-characters -whitespace-not-just-whitespace) –

回答

4
String.prototype.present = function() { 
    return this && this.trim() !== ''; 
}; 

如果該值可以是null,您不能使用原型方法測試,你可以使用一個功能。

function isPresent(string) { 
    return typeof string === 'string' && string.trim() !== ''; 
} 
+3

你會如何在值爲null的變量上調用它? –

+2

@HunterMcMillen你在我的邏輯中發現了一個嚴重錯誤... –

0

最好的是if語句或第一種方法,即。 string_present()函數。

0

您可以雙擊倒置變量:

> var a = ""; 
undefined 
> !a 
true 
> !!a 
false 
> var a = null; 
undefined 
> !!a 
false 
> var a = " "; 
> !!a.trim(); 
false 

而且比:

if (!!a && !!a.trim()) { 
    true 
}else{ 
    false 
} 
+0

失敗的情況'a =「」; !!'a' =>'true',但想要的是'false' – Zabba

+0

@Zabba我編輯我的答案爲你的情況:) –

+0

謝謝,但是這並不回答我的問題.. – Zabba