简体   繁体   English

如何使用underscore.js查找String是否为空?

[英]How to use underscore.js to find if a String is blank?

我看起来相当于http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isBlank(java.lang.CharSequence)我发现了几个第三方扩展,但是有一个开箱即用的下划线.js: http//underscorejs.org

Following @muistooshort's advice I created my mixin and wanted to share it: 按照@ muistooshort的建议,我创建了我的mixin并希望分享它:

  _.mixin({
    isBlank: function(string) {
      return (_.isUndefined(string) || _.isNull(string) || string.trim().length === 0)
    }
  });

> _("\t").isBlank()
< true

> _("qwerty").isBlank()
< false
_.isEmpty(_.trim(string));

This runs a null or empty string check. 这将运行null或空字符串检查。

Edited with update from ehftwelve 编辑来自ehftwelve的更新

function isBlank(str) {
  return !!(str||'').match(/^\s*$/);
}

isBlank(null);    // => true
isBlank('');      // => true
isBlank(' \t ');  // => true
isBlank(' foo '); // => false

In Underscore.js you have _.isEmpty ( http://underscorejs.org/#isEmpty ) but it only checks if the array-like object or string has a length of 0. _.isEmpty您有_.isEmptyhttp://underscorejs.org/#isEmpty ),但它只检查类似数组的对象或字符串的长度是否为0。

If you want to check if a variable is a whitespace string, empty string or null (equivalent of java's isBlank) you should make your own function. 如果要检查变量是否为空白字符串,空字符串或null(相当于java的isBlank),您应该创建自己的函数。

function isBlank(str) {

  if (str === null || str.length === 0 || str === " ") return true;
  return false;

}

using bind to create a native method: 使用bind创建本机方法:

var isBlank=/./.test.bind(/(^$)|(^null$)|(^\s+$)/); // bind a regexp to test()

_.map(["", " ", " x ", 0, null], isBlank ); // test it against various data
// == [true, true, false, false, true] // reflects java version output

You could extend underscore. 你可以扩展下划线。

  _.isBlank = function (str) {
        return !!(str||'').match(/^\s*$/);
    }

If you really don't want to create a function as taseenb mentioned use isEmpty with trim. 如果你真的不想创建一个函数作为taseenb提到使用isEmpty与trim。 Although this is ugly! 虽然这很难看!

_.isEmpty('    '.trim());

Although both these don't work with tabbed spaces 虽然这两个都不适用于标签空格

Here's my snippet that I used when checking empty strings. 这是我在检查空字符串时使用的代码片段。

    _.isBlank = function (str) {
       return (!str || /^\s*$/.test(str));
    }

    var strs = ['a', 1, -1, 0, NaN, '', ' ', '\t', '\n', null, undefined];
    strs.forEach(function(s){
     console.log('is blank? ', s, _.isBlank(s));
    });

Note: The zero(0) will be considered as empty. 注意:零(0)将被视为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM