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
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) {...}), since null, undefined, and '' are falsey values in JavaScript. 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 do null.property in JavaScript. BradM has probably the best solution to this. Commented Jul 25, 2013 at 20:56
  • Have a look at How can I check if string contains characters & whitespace, not just whitespace? Commented Jul 25, 2013 at 21:11

3 Answers 3

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() !== '';
}
Sign up to request clarification or add additional context in comments.

1 Comment

How would you call this on a variable with the value null?
0

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

Comments

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
}

1 Comment

Fails for the case a = " "; !!a => true but wanted is false

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.