js判断字符串是否全为空(使用trim函数/正则表达式)

时间:2021-09-17 15:56:00

我们需要判断用户输入的是否全是空格,可以使用以下方法:

方法一: 使用trim()

/* 使用String.trim()函数,来判断字符串是否全为空*/
function kongge1(test) {
let str = test.trim();
if (str.length == 0) {
console.log('字符串全是空格');
} else {
console.log('输入的字符串为:' + test);
}
}
如果 trim() 不存在,可以在所有代码前执行下面代码

/* 给String原型链对象添加方法trim */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}

例如:
/* 使用String.trim()函数,来判断字符串是否全为空*/
function kongge1(test) {

/* 给String原型链对象添加方法trim */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}

let str = test.trim();
if (str.length == 0) {
console.log('字符串全是空格');
} else {
console.log('输入的字符串为:' + test);
}
}

 

方法二: 使用正则表达式

/* 使用正则表达式来判断字符串是否全为空 */
function kongge2(test) {
if(test.match(/^\s+$/)){
console.log("all space or \\n");
}
if(test.match(/^[ ]+$/)){
console.log("all space")
}
if(test.match(/^[ ]*$/)){
console.log("all space or empty")
}
if(test.match(/^\s*$/)){
console.log("all space or \\n or empty")
} else {
console.log('输入的字符串为:' + test);
}
}

案例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js判断字符串是否全为空(使用trim函数/正则表达式)</title>
</head>
<body>
姓名:<input type="text" name="userName" id='userName' onblur="check(value)" value="">
<script type="text/javascript">
/*
typeof 检测给定变量的数据类型。
两种写法: typeof(value); typeof value;
可能返回的字符串:
"undefined" --- 如果这个值未定义。
"boolean" --- 如果这个值是布尔值。
"string" --- 如果这个值是字符串。
"number" --- 如果这个值是数值。
"object" --- 如果这个值是对象或者null;
"function" --- 如果这个值是函数。

*/
let str = 'str';
alert(typeof abc);//undefined;
alert(typeof undefined);//undefined
alert(typeof check(str));//undefined
alert(typeof '');//string
alert(typeof str);//string
alert(typeof 98);//number
alert(typeof {});//object
alert(typeof null);//object

function check(value) {
if ('string' == typeof value) {
kongge1(value);
kongge2(value);
} else {
console.log(typeof value);
console.log('请输入字符串');
}
}

/* 使用String.trim()函数,来判断字符串是否全为空*/
function kongge1(test) {
let str = test.trim();
if (str.length == 0) {
console.log('字符串全是空格');
} else {
console.log('输入的字符串为:' + test);
}
}

/* 使用正则表达式来判断字符串是否全为空 */
function kongge2(test) {
if(test.match(/^\s+$/)){
console.log("all space or \\n");
}
if(test.match(/^[ ]+$/)){
console.log("all space")
}
if(test.match(/^[ ]*$/)){
console.log("all space or empty")
}
if(test.match(/^\s*$/)){
console.log("all space or \\n or empty")
} else {
console.log('输入的字符串为:' + test);
}
}
</script>
</body>
</html>