js 判断字符串是否为空
在JavaScript中,可以使用以下方法来判断一个字符串是否为空:
- 使用
length属性:通过获取字符串的长度属性,判断字符串是否为空。如果字符串的长度为0,则说明字符串为空。
var str = "example";
if (str.length === 0) {
console.log("字符串为空");
} else {
console.log("字符串不为空");
}
- 使用
trim()方法:trim()方法可以去除字符串首尾的空格,如果去除空格后的字符串长度为0,则说明字符串为空。
var str = " ";
if (str.trim().length === 0) {
console.log("字符串为空");
} else {
console.log("字符串不为空");
}
- 使用正则表达式:使用正则表达式判断字符串是否只包含空格或者换行符。
var str = " ";
var regex = /^\s*$/;
if (regex.test(str)) {
console.log("字符串为空");
} else {
console.log("字符串不为空");
}
以上是三种常用的判断字符串是否为空的方法,可以根据实际情况选择合适的方法
原文地址: https://www.cveoy.top/t/topic/iL93 著作权归作者所有。请勿转载和采集!