日期:2014-05-16  浏览次数:20325 次

JS判断不能全部输入空格 和 去掉所有空格


//不能全部输入空格
<body>
<input type= "text " id= "1 " />
<input type= "button " value= "validator " id= "2 " onclick= "validator(); " />
</body>
</html>
<script>
function validator()
{
var var1 = document.getElementById( "1 ") ;
alert(var1);
var parten = /^\s*$/ ;
if(parten.test(var1))
alert( "all spaces! ") ;
else
alert( "not all spaces ");
}
</script>
<网友回复> <html>
<body>
<input type= "text " id= "1 " />
<input type= "button " value= "validator " id= "2 " onclick= "validator(); " />
IT 者

</body>
</html>
<script>
function validator()
{
var var1 = document.getElementById( "1 ") ;
alert(var1);

//这是正则,\s匹配空格和回车等
var parten = /^\s*$/ ;

//执行验证
if(parten.test(var1))
alert( "all spaces! ") ;
else
alert( "not all spaces ");
}
</script>

去除所有空格:
str = str.replace(/\s+/g,"");

去除两头空格:
str = str.replace(/^\s+|\s+$/g,"");
[color=red][/color]