JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

var x ="  ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
    alert("ya it is blank")
}

其他回答

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

if ((str?.trim()?.length || 0) > 0) {
   // str must not be any of:
   // undefined
   // null
   // ""
   // " " or just whitespace
}

或以函数形式:

const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;

const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

使用空合并运算符修剪空格:

if (!str?.trim()) {
  // do something...
}

我通常使用以下内容:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}