• 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;  
    }
  • 相关阅读:
    spring注解开发AnnotationConfigApplicationContext的使用
    java.rmi.server.ExportException: Port already in use: 1099; nested exception is
    mac 入门操作
    postgreSql 常用查询总结
    Tomcat专题
    Java反射
    notepad++ jstool 插件安装
    Java集合
    Java 集合并交补
    C++回调函数(callback)的使用
  • 原文地址:https://www.cnblogs.com/Chen-XiaoJun/p/6364227.html
Copyright © 2020-2023  润新知