zoukankan      html  css  js  c++  java
  • JavaScript 去除空格函数

     

    利用正则去除字符串前后空格的方法:

    function trim(strToTrim){

        return strToTrim.replace(/^\s+|\s+$/g,"")

    }

     

    function ltrim(strToTrim){

        return strToTrim.replace(/^\s+/,"");

    }

     

    function rtrim(strToTrim){

        return strToTrim.replace(/\s+$/,"");

    }

     

    我们可以把这些添加为String对象的子方法:

    String.prototype.trim = function(){

        return this.replace(/^s+|\s$/g,"");

    }

     

    String.prototype.ltrim = function(){

        return this.replace(/^s+/,"");

    }

     

    String.prototype.rtrim = function(){

        return this.replace(/\s+$/,"");

    }

     

    上面这种方法支持JavaScript1.2+以及Jscript3.0+,对于目前大多数的浏览器(4.0+)都可以支持,如果你需要支持更老的浏览器,可以使用下面这个例子,这能够去掉空格、空行、TAB、回车以及换页。

    var trim4old = {

        ltrim:function(strToTrim){

            for(var k=0; k < strToTrim.length && this.isWhiteSpace(strToTrim.charAt(k));k++);

            return strToTrim.substring(k,strToTrim.length);

        },

        rtrim:function(strTomTrim){

            for(var j = strTomTrim.length - 1;j>=0 && this.isWhiteSpace(strTomTrim.charAt(j));j--);

            return strTomTrim.substring(0,j+1);

        },

        trim:function(strToTrim){

            return this.rtrim(this.ltrim(strToTrim));

        },

        isWhiteSpace:function(strTomTrim){

            var whitespaceChars = "\t\n\r\f";

            return (whitespaceChars.indexOf(strTomTrim) != -1);

        }

    }

  • 相关阅读:
    maven 父子模块保持相同
    Maven deploy时排除指定的某个module
    源码,反码,补码
    Java日志之Slf4j,Log4J,logback原理总结
    Git Bash设置代理
    分享2个分布式锁
    二叉树的遍历记忆方法
    MySQL百万级数据分页查询及优化
    eclipse无法访问sun.misc.Unsafe类的解决办法
    Spring学习日志之纯Java配置的MVC框架搭建
  • 原文地址:https://www.cnblogs.com/cocowool/p/1299535.html
Copyright © 2011-2022 走看看