【解决方案】正则表达式判断字符串是否全是空格

用正则表达式实现:

var test = "   \n   ";
//var 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")
}


转自:js怎么判断字符串是不是全是空格


------------------------------------------- 2017.8.21 更新 ------------------------------------------

之前傻逼了,判断输入框的值是否全为空格的方法 用正则做 固然没错 但是太麻烦了 且不说代码复杂 最关键的是记不住这个正则表达式呀!!


好了 现在介绍一下最近刚学会的一招 巧妙运用 trim()

if( test.match(/^[ ]*$/) ){
    console.log("all space or empty")
}

以上代码等同于:

if( test.trim() ){
    console.log("all space or empty")
}


如果用于判断输入框的值是否全为空格,可以这样写:

var searchVal = $("#searchInput").val();

if ( !searchVal.trim() ) {

    alert("查询内容不能为空!");

    return false;

}


---------------------请注意-------------------------

 !searchVal.trim() 等于 searchVal.trim() == “”











posted @ 2016-12-02 15:54  Mr.Kay  阅读(5327)  评论(0编辑  收藏  举报