您的位置:首页 > Web前端 > JavaScript

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

2017-03-11 11:32 302 查看

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

方法一: 使用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);}}[code]

方法二: 使用正则表达式

/* 使用正则表达式来判断字符串是否全为空 */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);//undefinedalert(typeof check(str));//undefinedalert(typeof '');//stringalert(typeof str);//stringalert(typeof 98);//numberalert(typeof {});//objectalert(typeof null);//objectfunction 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: