我們需要判斷用戶輸入的是否全是空格,可以使用以下方法:
方法一: 使用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>