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


当前回答

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其空性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。

其他回答

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

if (!str.length) { ...

此外,如果您认为填充空白的字符串为“空”。

可以使用以下正则表达式进行测试:

!/\S/.test(string); // Returns true if blank.

您可以使用typeof运算符和length方法检查这一点。

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0

检查您是否试图传递未定义的术语也是一个好主意。

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。

嗯,检查这个的最简单的函数是。。。

const checkEmpty=string=>(strim.trim()==“”)||!strim.trim();

用法:

checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.

就是这么简单。:)