js判断字符串是否全为空(使⽤trim函数正则表达式)我们需要判断⽤户输⼊的是否全是空格,可以使⽤以下⽅法:
⽅法⼀:使⽤trim()
/* 使⽤im()函数,来判断字符串是否全为空*/
function kongge1(test) {
let str = im();
if (str.length == 0) {
console.log('字符串全是空格');
} else {
console.log('输⼊的字符串为:' + test);
}
}
如果 trim() 不存在,可以在所有代码前执⾏下⾯代码
/* 给String原型链对象添加⽅法trim */
if (!im) {
im = function () {
place(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
例如:
/* 使⽤im()函数,来判断字符串是否全为空*/
function kongge1(test) {
/* 给String原型链对象添加⽅法trim */
if (!im) {
im = function () {
place(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
let str = im();
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">
js正则表达式数字和小数点
<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('请输⼊字符串');
}
}
/* 使⽤im()函数,来判断字符串是否全为空*/        function kongge1(test) {
let str = im();
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>