源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

去除字符串左右两边的空格(实现代码)

  • 时间:2020-04-22 16:56 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:去除字符串左右两边的空格(实现代码)
在日常工作中,过滤表单中的一些特殊的字符是很常见的功能,比如文本中要求输入单纯的数字,但用户有时会误输入一些多余的空格或其他字符混合的文本,这显然不符合输入要求。
下面一起来学习怎么样去除字符串左右两边的空格。
过滤前:
  [img]http://files.jb51.net/file_images/article/201605/2016051210250410.png[/img]
过滤后:
  [img]http://files.jb51.net/file_images/article/201605/2016051210250411.png[/img]
HTML代码:
 <div class="main">
     <input id="userName" type="text" placeholder="请输入用户名">
     <input id="rule" type="button" value="过滤">
   </div>
CSS代码:
html,body,div,input{margin:0;padding:0;}
    .main{width:400px;height:auto;padding:0 15px;text-align:center;}
    .main input{width:100%;height:35px;border:none;margin-top:20px;border-radius:5px;}
    input[type="text"]{text-align:left;padding-left:15px;box-sizing:border-box;border:1px solid blue;}
    input[type="button"]{width:50%;background:blue;}
    @media only screen and (max-width: 415px) {
      .main{width:100%;box-sizing:border-box;}
    }
js部分:
var userName = document.getElementById('userName'),
        rule   = document.getElementById('rule'),
        regexEmpty = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;

    rule.onclick = function (){
      userName.value = userName.value.replace(regexEmpty,''); //正则替换
      console.log(userName.value);
    }
以上这篇去除字符串左右两边的空格(实现代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部