欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery replace方法去空格

程序员文章站 2023-11-18 13:38:04
话不多说,请看代码:

话不多说,请看代码:

<!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>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!