Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the equivalent of Rails `present?` in Javascript

Tags:

javascript

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
like image 664
Zabba Avatar asked Oct 03 '22 10:10

Zabba


1 Answers

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() !== '';
}
like image 137
Brad M Avatar answered Oct 05 '22 23:10

Brad M