JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
您可以很容易地将它添加到JavaScript中的原生String对象中,并反复使用它。。。如果您想检查“”空字符串,下面的代码可以为您完成这项工作:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
否则,如果您想同时检查“”空字符串和“”带空格,可以通过添加trim()来完成,类似于下面的代码:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
你可以这样称呼它:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
其他回答
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' />
这也是检查字段是否为空的通用方法。
非常通用的“All-In-One”功能(但不推荐):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
您可以很容易地将它添加到JavaScript中的原生String对象中,并反复使用它。。。如果您想检查“”空字符串,下面的代码可以为您完成这项工作:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
否则,如果您想同时检查“”空字符串和“”带空格,可以通过添加trim()来完成,类似于下面的代码:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
你可以这样称呼它:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
检查您是否试图传递未定义的术语也是一个好主意。
function TestMe() {
if((typeof str != 'undefined') && str) {
alert(str);
}
};
TestMe();
var str = 'hello';
TestMe();
我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。
空字符串,未定义,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
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔