javascript 中的 trim

在javascript中的string对象没有trim方法,所以trim功能需要自己实现: 
代码如下:

  1. ﹤scriptlanguage=”javascript”﹥  
  2. /** 
  3. *删除左右两端的空格 
  4. */  
  5. String.prototype.trim=function(){     
  6.     return this.replace(/(^\s*)|(\s*$)/g, '');  
  7. }    
  8. /** 
  9. *删除左边的空格 
  10. */  
  11. String.prototype.ltrim=function()  
  12. {  
  13.   return this.replace(/(^s*)/g,'');  
  14. }  
  15. /** 
  16. *删除右边的空格 
  17. */  
  18. String.prototype.rtrim=function()  
  19. {  
  20.   return this.replace(/(s*$)/g,'');  
  21. }  
  22. ﹤/script﹥  

 

使用如下:

 

 

  1. ﹤scripttype=”text/javascript”﹥  
  2.   alert(document.getElementById(’abc’).value.trim());  
  3.   alert(document.getElementById(’abc’).value.ltrim());  
  4.   alert(document.getElementById(’abc’).value.rtrim());  
  5. ﹤/script﹥  

 

 

另外一种方法是写一个trim的函数,函数如下:

function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" ); 
} 

 

 

 

 

你可能感兴趣的:(JavaScript,prototype)