javascript實現trim的方法

javascript中沒有對字符串的前,後空格去除的方法,最近項目需要,所以自己寫了一個,感覺還不錯,拿出來和大家分享.

 

  1. <html> 
  2.     <head> 
  3.         <script language="javascript"> 
  4.          
  5.             String.prototype.ltrim = function(){return this.replace(/^\s+/g,"");} 
  6.             String.prototype.rtrim = function(){return this.replace(/\s+$/g,"");}          
  7.             String.prototype.trim = function(){return this.replace(/(^s+|\s+$/g, "");} 
  8.  
  9.             function change(){               
  10.                 var strTmp = document.getElementById("text1").value; 
  11.                 var strL = strTmp.ltrim(); 
  12.                 var strR = strTmp.rtrim(); 
  13.                 var str = strTmp.trim(); 
  14.                 document.getElementById("text2").value = strL
  15.                 document.getElementById("text3").value = strR
  16.                 document.getElementById("text4").value = str
  17.             } 
  18.          
  19.         </script> 
  20.     </head> 
  21.      
  22.     <body> 
  23.         with space string:<input type="text" name="text1" id="text1" value="    aaa    "/><br>   
  24.         trim left space:<input type="text" name="text2" id="text2" value=""/><br> 
  25.         trim right space:<input type="text" name="text3" id="text3" value=""/><br> 
  26.         trim left and right sapce:  <input type="text" name="text4" id="text4" value=""/><br> 
  27.         <input type="button" value="CLICK" onclick="change()"/> 
  28.     </body> 
  29.  
  30. </html> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章