Make Rails equivalent to `present?` In Javascript

In Rails, can we .present? check if there is a nil line and contains something other than a space or an empty line:

 "".present? # => false " ".present? # => false nil.present? # => false "hello".present? # => true 

I would like for similar functionality in Javascript, without having to write a function for it, like function string_present?(str) { ... }

Can I do something with Javascript out of the box, or by adding a String prototype?

I have done this:

 String.prototype.present = function() { if(this.length > 0) { return this; } return null; } 

But how would I do this work:

 var x = null; x.present var y; y.present 
+4
source share
3 answers
 String.prototype.present = function() { return this && this.trim() !== ''; }; 

If the value can be null , you cannot use the prototype approach for testing, you can use the function.

 function isPresent(string) { return typeof string === 'string' && string.trim() !== ''; } 
+4
source

Best of all is this statement or the first approach, i.e. string_present ().

0
source

You can double the 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 } 
0
source

Source: https://habr.com/ru/post/1493524/


All Articles