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
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
Share
Improve this question
asked Jul 25, 2013 at 20:47
ZabbaZabba
65.5k48 gold badges182 silver badges211 bronze badges
3
-
2
If you didn't have the "could also be only whitespace" requirement, then you could simply use the string variable in any boolean statement (e.g.
if (myStr) {...}
), sincenull
,undefined
, and''
are falsey values in JavaScript. – ajp15243 Commented Jul 25, 2013 at 20:53 -
1
On further reflection, I don't think you're going to get something as "nice looking" as
.present?
, since you cannot donull.property
in JavaScript. BradM has probably the best solution to this. – ajp15243 Commented Jul 25, 2013 at 20:56 - Have a look at How can I check if string contains characters & whitespace, not just whitespace? – Felix Kling Commented Jul 25, 2013 at 21:11
3 Answers
Reset to default 4String.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() !== '';
}
The best is if statement or first one approach, ie. string_present() function.
You can double invert variable:
> var a = "";
undefined
> !a
true
> !!a
false
> var a = null;
undefined
> !!a
false
> var a = " ";
> !!a.trim();
false
And than:
if (!!a && !!a.trim()) {
true
}else{
false
}