最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Making the equivalent of Rails `present?` in Javascript - Stack Overflow

programmeradmin0浏览0评论

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) {...}), since null, 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 do null.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
Add a ment  | 

3 Answers 3

Reset to default 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() !== '';
}

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
}
发布评论

评论列表(0)

  1. 暂无评论