In Rails we can .present?
to check if a string is not-nil
and contains something other than white-space or an empty string:
"".present? # => false
" ".present? # => false
nil.present? # => false
"hello".present? # => true
I would like similar functionality in Javascript, without having to write a function for it like function string_present?(str) { ... }
Is this something I can do with Javascript out-of-the-box or by adding to the String
's prototype?
I did this:
String.prototype.present = function()
{
if(this.length > 0) {
return this;
}
return null;
}
But, how would I make this work:
var x = null; x.present
var y; y.present
String.prototype.present = function() {
return this && this.trim() !== '';
};
If the value can be null
, you can't use the prototype approach to test, you can use a function.
function isPresent(string) {
return typeof string === 'string' && string.trim() !== '';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With