'IsNullOrWhitespace' in JavaScript?

'IsNullOrWhitespace' in JavaScript?

本文关键字:JavaScript IsNullOrWhitespace in      更新时间:2023-09-26

是否有一个JavaScript等效于。net的String.IsNullOrWhitespace,以便我可以检查客户端上的文本框是否有任何可见的文本?

我宁愿先在客户端执行此操作,而不是返回文本框值并仅依赖服务器端验证,尽管我也会这样做。

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

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}

这是jsFiddle。下面的笔记。


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

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

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

function isNullOrWhitespace( input ) {
  return !input || input.replace(/'s/g, '').length < 1;
}

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

function isNullOrWhitespace( input ) {
  return !input || input.trim().length < 1;
}

并在混合中添加更多的错误,产生最终(简化)版本:

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}

自己动手很容易:

function isNullOrWhitespace( input ) {
    if (typeof input === 'undefined' || input == null) return true;
    return input.replace(/'s/g, '').length < 1;
}

没有,但是你可以写一个

function isNullOrWhitespace( str )
{
  // Does the string not contain at least 1 non-whitespace character?
  return !/'S/.test( str );
}

试试

检查字符串是否为undefined, null,非字符串类型,空或空格(s

)
/**
  * Checks the string if undefined, null, not typeof string, empty or space(s)
  * @param {any} str string to be evaluated
  * @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
    return str === undefined || str === null
                             || typeof str !== 'string'
                             || str.match(/^ *$/) !== null;
}

你可以这样使用

isStringNullOrWhiteSpace('Your String');

你必须自己写:

function isNullOrWhitespace(strToCheck) {
    var whitespaceChars = "'s";
    return (strToCheck === null || whitespaceChars.indexOf(strToCheck) != -1);
}

trim()是JS缺少的一个有用的字符串函数。

添加:

String.prototype.trim = function() { return this.replace(/^'s+|'s+$/g,"") }

Then: if (document.form.field.value.trim() == "")

将两个最佳答案的相关部分提取出来,你会得到这样的结果:

function IsNullOrWhitespace(input) {
    if (typeof input === 'undefined' || input == null) return true;
    return !/'S/.test(input); // Does it fail to find a non-whitespace character?
}

这个答案的其余部分仅供那些对这个答案和Dexter的答案之间的性能差异感兴趣的人使用。两者都会产生相同的结果,但是这段代码稍微快一些。

在我的计算机上,对以下代码使用QUnit测试:

var count = 100000;
var start = performance.now();
var str = "This is a test string.";
for (var i = 0; i < count; ++i) {
    IsNullOrWhitespace(null);
    IsNullOrWhitespace(str);
}
var end = performance.now();
var elapsed = end - start;
assert.ok(true, "" + count + " runs of IsNullOrWhitespace() took: " + elapsed + " milliseconds.");

结果如下:

  • RegExp。替换方法= 33 - 37毫秒
  • RegExp。测试方法= 11 - 14毫秒

您可以使用正则表达式/'S/来测试字段是否为空白,并将其与空检查结合使用。

,

if(textBoxVal === null || textBoxVal.match(/'S/)){
    // field is invalid (empty or spaces)
}