zoukankan      html  css  js  c++  java
  • JavaScript清除字符串前后空格

    一、通过循环检查,然后提取非空格字符串

    //去掉前后空白
    function trim(s){ 
      return trimRight(trimLeft(s)); 
    } 
    //去掉左边的空白
    function trimLeft(s){ 
      if(s == null) { 
        return ""; 
      } 
      var whitespace = new String(" 	
    
    "); 
      var str = new String(s); 
      if (whitespace.indexOf(str.charAt(0)) != -1) { 
        var j=0, i = str.length; 
        while (j < i && whitespace.indexOf(str.charAt(j)) != -1){ 
          j++; 
        } 
        str = str.substring(j, i); 
      } 
      return str; 
    } 
     
    //去掉右边的空白 www.jb51.net
    function trimRight(s){ 
      if(s == null) return ""; 
      var whitespace = new String(" 	
    
    "); 
      var str = new String(s); 
      if (whitespace.indexOf(str.charAt(str.length-1)) != -1){ 
        var i = str.length - 1; 
        while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){ 
          i--; 
        } 
        str = str.substring(0, i+1); 
      } 
      return str; 
    }     

    二、通过正则替换

    //前后
    String.prototype.trim = function() 
    { 
    return this.replace(/(^s*)|(s*$)/g, ""); 
    } 
    //
    String.prototype.trimLeft = function() 
    { 
    return this.replace(/(^s*)/g, ""); 
    } 
    //
    String.prototype.trimRight = function() 
    { 
    return this.replace(/(s*$)/g, ""); 
    } 

    //去左空格;
    function trimLeft(s){
      return s.replace(/(^s*)/g, "");
    }
    //去右空格;
    function trimRight(s){
      return s.replace(/(s*$)/g, "");
    }
    //去左右空格;
    function trim(s){
      return s.replace(/(^s*)|(s*$)/g, "");
    }

    三、jQuery自带方法

    $.trim(str)

    内部实现:

    function trim(str){  
      return str.replace(/^(s|u00A0)+/,'').replace(/(s|u00A0)+$/,'');  
    }

    四、裁剪

    function trim(str){  
      str = str.replace(/^(s|u00A0)+/,'');  
      for(var i=str.length-1; i>=0; i--){  
        if(/S/.test(str.charAt(i))){  
          str = str.substring(0, i+1);  
          break;  
        }  
      }  
      return str;  
    }
  • 相关阅读:
    复数除法
    base operand of '->' has non-pointer type 'const Comple
    virtual关键字
    & 引用
    const用法
    Iptable与firewalld防火墙
    存储结构与磁盘划分
    Linux系统中用户身份与文件权限
    计时器小程序——由浅入深实例讲解
    ASP.NET编程十大技巧(他人总结)
  • 原文地址:https://www.cnblogs.com/Chen-XiaoJun/p/6364227.html
Copyright © 2011-2022 走看看