JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
另一种方式,但我相信bdukes的答案是最好的。
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');
其他回答
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
当测试未定义或为空时,需要进行类型检查以避免运行时错误。
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")
}
最接近str.Empty(前提是str是String)的是:
if (!str.length) { ...
这是一个错误的值。
第一种解决方案:
const str = "";
return str || "Hello"
第二种解决方案:
const str = "";
return (!!str) || "Hello"; // !!str is Boolean
第三种解决方案:
const str = "";
return (+str) || "Hello"; // !!str is Boolean
Try:
if (str && str.trim().length) {
//...
}
推荐文章
- 如何在禁用按钮上启用引导工具提示?
- Node.js全局变量
- 在前一个函数完成后调用另一个函数
- JavaScript中两个日期之间的月份差异
- 如何同时运行两个jQuery动画?
- 如何将FormData (HTML5对象)转换为JSON
- Object.hasOwnProperty()产生ESLint 'no-prototype-builtins'错误:如何修复?
- 如何将Node.js流的内容读入字符串变量?
- 两个感叹号?
- 如何在JavaScript中计算今天之前三个月的日期?
- <script defer="defer">到底是如何工作的?
- 设置ajax超时
- 为什么JavaScript需要以“;”开头?
- 既然JavaScript和Java没有任何关系,它为什么被称为JavaScript ?
- 当你双击日文文本时,Chrome如何决定突出显示什么?