JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
其他回答
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
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;
尝试以下代码:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
使用空合并运算符修剪空格:
if (!str?.trim()) {
// do something...
}
我通常使用以下内容:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔