JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
其他回答
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
试试这个
str.value.length == 0
我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:
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空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
// Now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
这也是检查字段是否为空的通用方法。
使用空合并运算符修剪空格:
if (!str?.trim()) {
// do something...
}