11.为String类扩展trim方法

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 2 "http://www.w3.org/TR/html4/loose.dtd">
 3 <html>
 4 <head>
 5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 6 <title>无标题文档</title>
 7 <script type="text/javascript">
 8 
 9     var username="    sf fss      ";
10     //alert("-->"+username.trim()+"<--");//js中的trim方法可以用来去除字符串的前后空格;但是在ie浏览器中无法使用
11     
12     //使用自己扩展的trim方法
13     String.prototype.trim=function(){
14     
15         //return this.replace("前空格","").replace("后空格","");//this代表调用该函数的字符串
16         /*
17         前空白的正则表达式对象:/^s+/
18         后空白的正则表达式对象:/s+$/
19         
20         */
21         return this.replace(/^s+/,"").replace(/s+$/,"");
22     
23     }
24     
25     alert("-->"+username.trim()+"<--");
26 
27 </script>
28 </head>
29 
30 <body>
31 </body>
32 </html>
原文地址:https://www.cnblogs.com/xuzhiyuan/p/7874991.html