JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
检查是否为字符串类型,如果不为空:
const isNonEmptyString = (val) => typeof val === 'string' && !!val
其他回答
最接近str.Empty(前提是str是String)的是:
if (!str.length) { ...
如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
同时,我们可以有一个函数来检查所有“空”,如null、undefined、“”、“”,{}、[]。所以我写了这个。
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
用例和结果。
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // 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' />
这也是检查字段是否为空的通用方法。
您可以验证以下方法并了解其区别。
var j=未定义;console.log((typeof j==“undefined”)?“真”:“假”);var j=空;console.log((j==null)?“真”:“假”);var j=“”;console.log((!j)?“真”:“假”);var j=“Hi”;console.log((!j)?“真”:“假”);
推荐文章
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- getActivity()在Fragment函数中返回null
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法