6

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
Zabba
  • 64,285
  • 47
  • 179
  • 207
  • 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) {...}`), since `null`, `undefined`, and `''` are falsey values in JavaScript. – ajp15243 Jul 25 '13 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 do `null.property` in JavaScript. BradM has probably the best solution to this. – ajp15243 Jul 25 '13 at 20:56
  • Have a look at [How can I check if string contains characters & whitespace, not just whitespace?](http://stackoverflow.com/questions/2031085/how-can-i-check-if-string-contains-characters-whitespace-not-just-whitespace) – Felix Kling Jul 25 '13 at 21:11

3 Answers3

4
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() !== '';
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
Brad M
  • 7,857
  • 1
  • 23
  • 40
0

The best is if statement or first one approach, ie. string_present() function.

Jacek
  • 412
  • 4
  • 9
0

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
}
Alexander Vagin
  • 575
  • 1
  • 8
  • 15