去除字符串左右两边的空格

在日常工作中,过滤表单中的一些特殊的字符是很常见的功能,比如文本中要求输入单纯的数字,但用户有时会误输入一些多余的空格或其他字符混合的文本,这显然不符合输入要求。
     下面一起来学习怎么样去除字符串左右两边的空格。
  过滤前:
  
  过滤后:
  
HTML代码:
1 <div class="main">
2         <input id="userName" type="text" placeholder="请输入用户名">
3         <input id="rule" type="button" value="过滤">
4     </div>

CSS代码:

1 html,body,div,input{margin:0;padding:0;}
2         .main{width:400px;height:auto;padding:0 15px;text-align:center;}
3         .main input{width:100%;height:35px;border:none;margin-top:20px;border-radius:5px;}
4         input[type="text"]{text-align:left;padding-left:15px;box-sizing:border-box;border:1px solid blue;}
5         input[type="button"]{width:50%;background:blue;}
6         @media only screen and (max-width: 415px) {
7             .main{width:100%;box-sizing:border-box;}
8         }

js部分:

1 var userName = document.getElementById('userName'),
2                 rule     = document.getElementById('rule'),
3                 regexEmpty = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
4 
5         rule.onclick = function (){
6             userName.value = userName.value.replace(regexEmpty,''); //正则替换
7             console.log(userName.value);
8         }

demo演示地址:

posted on 2016-05-12 08:49  择哥灬仰望星空  阅读(1234)  评论(0编辑  收藏  举报

导航