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>
相关推荐
shqhope 2020-06-23
满地星辰 2020-09-16
WebVincent 2020-06-16
lynjay 2020-06-14
ajaxtony 2020-06-11
有梦就能实现 2020-06-05
zhendeshifeng 2020-05-27
gcgl000hugang 2020-02-10
Yasin 2020-05-05
Darklovy 2020-04-16
hellobabygogo 2020-03-06
程松 2020-02-23
wbingyang 2020-02-16
文山羊 2020-02-14
zehuawong 2020-02-11
jiahaohappy 2020-01-10
ELEMENTS爱乐冬雨 2019-12-29