javascript实现trim..
时间:2010-10-15 来源:xharvard
javascript中没有对字符串的前,后空格去除的方法,最近项目需要,所以自己写了一个,感觉还不错,拿出来和大家分享.
- <html>
- <head>
- <script language="javascript">
- String.prototype.ltrim = function(){return this.replace(/(^\s*)/g,"");}
- String.prototype.rtrim = function(){return this.replace(/(\s*$)/g,"");}
- String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g, "");}
- function change(){
- var strTmp = document.getElementById("text1").value;
- var strL = strTmp.ltrim();
- var strR = strTmp.rtrim();
- var str = strTmp.trim();
- document.getElementById("text2").value = strL;
- document.getElementById("text3").value = strR;
- document.getElementById("text4").value = str;
- }
- </script>
- </head>
- <body>
- with space string:<input type="text" name="text1" id="text1" value=" aaa "/><br>
- trim left space:<input type="text" name="text2" id="text2" value=""/><br>
- trim right space:<input type="text" name="text3" id="text3" value=""/><br>
- trim left and right sapce: <input type="text" name="text4" id="text4" value=""/><br>
- <input type="button" value="CLICK" onclick="change()"/>
- </body>
- </html>
相关阅读 更多 +