yangzailu

导航

jquery replace方法去空格

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <link rel="stylesheet" type="text/css" href="" />
  <style type="text/css"></style>
  <script type="text/javascript" src="jquery-3.0.0.js"></script>
 </head>

 <body>
  <div style="width:300px;height:100px;border:1px solid #E5E5E5;margin:0 auto;margin-top:30px;">
  <form action="" method="post">
    <span>用户名:</span><input type="text" name="username" class="username" value="" />
    <input type="submit" value="提交" class="tijiao">
  </form>
    <script type="text/javascript">
    $(document).ready(function(){
        $(".tijiao").click(function(){
             //var name = $.trim($(".username").val());
             var name=  $('input[name=username]').val().replace(/(^\s*)|(\s*$)/g,"");
             if(name==""){
                alert("用户名不能为空");
             }
         });
    });

    /*
        /(^\s*)|(\s*$)/g  包含以空格、回车符等字符开头或者空格、回车符等字符结尾的字符串,可过滤出所有空格、回车符的字符
        /g意思就是:global可选标志,带这个标志表示替换将针对行中每个匹配的串进行,否则则只替换行中第一个匹配串。如:we.fdffddfwe.加上/g后,则2个we都会出来;
        \s 空白字符

        replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
        stringObject.replace(regexp/substr,replacement)
    */
    </script>
  <div>
 </body>
</html>

 

posted on 2017-04-21 14:31  飞离地平线  阅读(545)  评论(0编辑  收藏  举报