JavaScript中的"IsNullOrWhitespace"?

Sco*_*ott 54 .net javascript string isnullorempty is-empty

是否有一个与.NET相当的JavaScript,String.IsNullOrWhitespace以便我可以检查客户端的文本框中是否有任何可见文本?

我宁愿在客户端做这个,而不是回发文本框值,只依靠服务器端验证,即使我也会这样做.

Dex*_*ter 71

滚动你自己很容易:

function isNullOrWhitespace( input ) {

    if (typeof input === 'undefined' || input == null) return true;

    return input.replace(/\s/g, '').length < 1;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用正则表达式而不是`trim()`? (3认同)

小智 57

对于简洁的现代跨浏览器实现,只需:

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}
Run Code Online (Sandbox Code Playgroud)

这是jsFiddle.以下注释.


目前接受的答案可以简化为:

function isNullOrWhitespace( input ) {
  return (typeof input === 'undefined' || input == null)
    || input.replace(/\s/g, '').length < 1;
}
Run Code Online (Sandbox Code Playgroud)

并利用虚假,甚至进一步:

function isNullOrWhitespace( input ) {
  return !input || input.replace(/\s/g, '').length < 1;
}
Run Code Online (Sandbox Code Playgroud)

trim()在所有最近的浏览器中都可用,因此我们可以选择删除正则表达式:

function isNullOrWhitespace( input ) {
  return !input || input.trim().length < 1;
}
Run Code Online (Sandbox Code Playgroud)

并添加更多的虚假混合,产生最终(简化)版本:

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果输入不是字符串,这可能会失败并出现“未捕获的类型错误:input.trim不是函数”。 (2认同)