用开箱即用的jquery测试空字符串的最好方法是什么,即没有插件?我试过这个。
但至少在开箱即用时行不通。使用内置的东西会很好。
我不想重复
if (a == null || a=='')
where if some if (isempty(a))将可用。
用开箱即用的jquery测试空字符串的最好方法是什么,即没有插件?我试过这个。
但至少在开箱即用时行不通。使用内置的东西会很好。
我不想重复
if (a == null || a=='')
where if some if (isempty(a))将可用。
当前回答
试试这个
if(!a || a.length === 0)
其他回答
if(!my_string){
// stuff
}
and
if(my_string !== "")
如果你想接受空值但拒绝空值
编辑:哎呀,忘记你的条件是如果它是空的
因为你也可以输入数字以及固定类型的字符串,答案实际上应该是:
function isBlank(value) {
return $.trim(value);
}
尝试在浏览器控制台或node.js repl中执行此命令。
var string = ' ';
string ? true : false;
//-> true
string = '';
string ? true : false;
//-> false
因此,一个简单的分支结构就足够测试了。
if(string) {
// string is not empty
}
根据David的回答,我个人喜欢首先检查给定的对象,如果它是一个字符串。否则,在一个不存在的对象上调用.trim()将引发异常:
function isEmpty(value) {
return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}
用法:
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false
if((a.trim()=="")||(a=="")||(a==null))
{
//empty condition
}
else
{
//working condition
}