js判断输入字符串是否为空、空格、null的方法总结

判断字符串是否为空

var strings = ''; 
if (string.length == 0) 
{ 
  alert('不能为空'); 
}

判断字符串是否为“空”字符即用户输入了空格

var strings = ' '; 
if (strings.replace(/(^s*)|(s*$)/g, "").length ==0) 
{ 
  alert('不能为空'); 
}

判断输入字符串是否为空或者全部都是空格

function isNull( str ){
if ( str == "" ) return true;
var regu = "^[ ]+$";
var re = new RegExp(regu);
return re.test(str);
}

如果有null时上面代码就无法正常判断了,下面代码是判断为null的情况

var exp = null; 
if (exp == null) 
{ 
  alert("is null"); 
}

exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。

注意:要同时判断 null 和 undefined 时可使用本法。 代码如下

var exp = null; 
if (!exp) 
{ 
  alert("is null"); 
}

如果 exp 为 undefined,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined、数字零、false 时可使用本法。代码如下

var exp = null; 
if (typeof exp == "null") 
{ 
  alert("is null"); 
}

 

posted @ 2022-04-29 20:24  每天进步多一点  阅读(8818)  评论(0)    收藏  举报