JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
有很多答案,还有很多不同的可能性!
毫无疑问,快速简单的实现是赢家:if(!str.length){…}
然而,还有许多其他例子。我建议,最好的功能方法是:
函数为空(str){if(str类型==‘undefined‘||!str | | str.length==0 | | str==“”||!/[^\s]/.test(str)||/^\s*$/.test(str)|| str.replace(/\s/g,“”)==“)返回true;其他的return false;}
我知道有点过分了。
其他回答
Undercore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。
参考:http://underscorejs.org/#isEmpty
isEmpty _.isEmpty(对象)如果可枚举对象不包含值(无可枚举的所有者属性),则返回true。对于字符串和类似数组的对象_.isEmpty检查长度属性是否为0。_.is空([1,2,3]);=>假_.isEmpty({});=>真
其他非常有用的Undercore.js函数包括:
http://underscorejs.org/#isNull_.isNull(对象)http://underscorejs.org/#isUndefined_.is未定义(值)http://underscorejs.org/#has_.有(对象,键)
空字符串,未定义,null。。。
检查真实值:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
要检查错误值,请执行以下操作:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
空字符串(仅限!)
要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:
if (strValue === "") {
// strValue was empty string
}
要严格检查非空字符串,请使用!==操作员:
if (strValue !== "") {
// strValue was not an empty string
}
为了检查变量是否为false,或者它的长度属性是否等于零(对于字符串,这意味着它为空),我使用:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(请注意,字符串不是唯一具有长度属性的变量,例如,数组也有它们。)
或者,您可以使用(并非如此)新可选的链接和箭头函数来简化:
const isEmpty = (str) => (!str?.length);
它将检查长度,如果为空值,则返回undefined,而不会抛出错误。在空值的情况下,零是错误的,结果仍然有效。
为了检查变量是否为false,或者字符串是否仅包含空格或为空,我使用:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
如果需要,您可以像这样对String原型进行猴式修补:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
请注意,monkey修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
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")
}