replace is a very important knowledge point. This article mainly introduces the relevant knowledge of jquery replace method to remove spaces, which has a good reference value. Let's take a look with the editor below, I hope it can help everyone.
Without further ado, please take a look at the code:
<!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> <p 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> <p> </body> </html>
Related recommendations:
Detailed explanation of JS regular replacement method to remove spaces
Usage of space removal function in python
javascript trim Space removal function implementation code_javascript skills
The above is the detailed content of jquery uses replace to remove spaces. For more information, please follow other related articles on the PHP Chinese website!