JS去除字符串左右两端的空格(转载)

来源:https://www.cnblogs.com/fanyf/p/3785387.html

var str='     测试     ';


一、函数
  <script type="text/javascript">
   function trim(str){ //删除左右两端的空格
       return str.replace(/(^s*)|(s*$)/g, "");
   }
   function ltrim(str){ //删除左边的空格
       return str.replace(/(^s*)/g,"");
   }
   function rtrim(str){ //删除右边的空格
       return str.replace(/(s*$)/g,"");
   }

函数调用  trim(str)

二、js对象的方法

        String.prototype.trim=function(){
      return this.replace(/(^s*)|(s*$)/g, "");
   }
   String.prototype.ltrim=function(){
      return this.replace(/(^s*)/g,"");
   }
   String.prototype.rtrim=function(){
      return this.replace(/(s*$)/g,"");
   }


类中方法调用 str.trim();

三、将公共方法提取到一个或多个公共js文件,需要的时候直接引用;

原文地址:https://www.cnblogs.com/hao-1234-1234/p/11150348.html