JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
其他回答
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
当测试未定义或为空时,需要进行类型检查以避免运行时错误。
有很多答案,还有很多不同的可能性!
毫无疑问,快速简单的实现是赢家: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;}
我知道有点过分了。
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
您可以很容易地将它添加到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
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
或以函数形式:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类