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


当前回答

另一种方式,但我相信bdukes的答案是最好的。

var myString = 'hello'; 
if(myString.charAt(0)){
    alert('no empty');
}
alert('empty');

其他回答

没有isEmpty()方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

当测试未定义或为空时,需要进行类型检查以避免运行时错误。

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")
}

最接近str.Empty(前提是str是String)的是:

if (!str.length) { ...

这是一个错误的值。

第一种解决方案:

const str = "";
return str || "Hello"

第二种解决方案:

const str = "";
return (!!str) || "Hello"; // !!str is Boolean

第三种解决方案:

const str = "";
return (+str) || "Hello"; // !!str is Boolean

Try:

if (str && str.trim().length) {  
    //...
}