js去除首尾空格

简单的:str = jQuery.trim(str);

1 var temp = " aa b   ";
2 console.log("cc" + temp);
3 temp = jQuery.trim(temp);
4 console.log("cc" + temp);

自己写的:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title></title>
 6     <script src="Js/jquery-1.8.2.min.js"></script>
 7     <script type="text/javascript">
 8         function trim(str) {
 9             str = str.replace(/^(\s|\u00A0)+/, '');
10             for (var i = str.length - 1; i >= 0; i--) {
11                 if (/\S/.test(str.charAt(i))) {
12                     str = str.substring(0, i + 1);
13                     break;
14                 }
15             }
16             return str;
17         }
18         $(function () {
19             $("#bt").click(function () {
20                 var temp = $('#tes');
21                 var c = temp[0];
22                 alert('test' + trim(temp.val()) + 'str')
23             })
24         })
25     </script>
26 </head>
27 <body>
28     输入:<input id="tes" type="text" /><br />
29     <input id="bt" type="button" value="检测" />
30 </body>
31 </html>
posted @ 2014-12-25 08:47  Wangyk  阅读(1157)  评论(0编辑  收藏  举报