JavaScript 中的“IsNullOrWhitespace”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5559425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:48:26  来源:igfitidea点击:

'IsNullOrWhitespace' in JavaScript?

javascript.netstringis-emptyisnullorempty

提问by Scott

Is there a JavaScript equivalent to .NET's String.IsNullOrWhitespaceso that I can check if a textbox on the client-side has any visible text in it?

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

I'd rather do this on the client-side first than post back the textbox value and rely only on server-side validation, even though I will do that as well.

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

回答by Dexter

It's easy enough to roll your own:

自己动手很容易:

function isNullOrWhitespace( input ) {

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

    return input.replace(/\s/g, '').length < 1;
}

回答by Dexter

For a succinct modern cross-browser implementation, just do:

对于简洁的现代跨浏览器实现,只需执行以下操作:

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

Here's the jsFiddle. Notes below.

这是jsFiddle。注释如下。



The currently accepted answercan be simplified to:

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

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

And leveraging falsiness, even further to:

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

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

trim() is available in all recent browsers, so we can optionally drop the regex:

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

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

And add a little more falsiness to the mix, yielding the final (simplified) version:

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

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

回答by Peter Bailey

no, but you could write one

不,但你可以写一个

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

回答by T4NK3R

trim()is a useful string-function that JS is missing..

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

Add it:

添加它:

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

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

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

回答by lukastymo

You must write your own:

你必须自己写:

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

回答by John Fisher

Pulling the relevant parts of the two best answers, you get something like this:

拉出两个最佳答案的相关部分,您会得到如下内容:

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

The rest of this answer is only for those interested in the performance differences between this answer and Dexter's answer. Both will produce the same results, but this code is slightly faster.

此答案的其余部分仅适用于对此答案与 Dexter 的答案之间的性能差异感兴趣的人。两者都会产生相同的结果,但此代码稍快。

On my computer, using a QUnit test over the following code:

在我的计算机上,对以下代码使用 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.");

The results were:

结果是:

  • RegExp.replace method = 33 - 37 milliseconds
  • RegExp.test method = 11 - 14 milliseconds
  • RegExp.replace 方法 = 33 - 37 毫秒
  • RegExp.test 方法 = 11 - 14 毫秒

回答by Rod lauro Romarate

Try this out

试试这个

/**
  * 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;
}

You can use it like this

你可以像这样使用它

isStringNullOrWhiteSpace('Your String');

回答by McStretch

You can use the regex /\S/to test if a field is whitespace, and combine that with a null check.

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

Ex:

前任:

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