zoukankan      html  css  js  c++  java
  • javascript模仿php 函数 trim ltrim rtrim (原创)

    javascript模仿php 函数 trim  ltrim rtrim,去除字符串两边空格或其他符号

    本文地址:js trim js php trim

     function trims(){
        this.init = function(myarguments){
            if(arguments.length===0){return false;}
            this.arg = myarguments;
            this.len = this.arg.length;
            if(this.len>0){ this.str = this.arg[0]; }
            if(this.len>1){ this.thechar = this.arg[1]; }
            if(typeof this.thechar=='undefined'){
                this.rg_l = new RegExp("^(\s|\u00A0)+");
                this.rg_r = new RegExp("\S");
            }else{
                this.rg_l = new RegExp("^("+this.thechar+")+");
                this.rg_r = new RegExp("[^"+this.thechar+"]{1}");    
            }        
        };
        if (typeof trims._initialized == "undefined") {
            trims.prototype.ltrim = function() {
              this.str = this.str.replace(this.rg_l,'');
            };
            trims.prototype.rtrim = function() {
                for(var i=this.str.length-1; i>=0; i--){
                    if(this.rg_r.test(this.str.charAt(i))){  
                        this.str = this.str.substring(0, i+1);  
                        break;
                    }
                }
            };
            trims._initialized = true;
        }  
    };
    var trimsobj = new trims();
    function trim(){
        trimsobj.init(arguments);
        trimsobj.ltrim();
        trimsobj.rtrim();
        return trimsobj.str;
    }
    function rtrim(){
        trimsobj.init(arguments);
        trimsobj.rtrim();
        return trimsobj.str;
    }
    function ltrim(){
        trimsobj.init(arguments);
        trimsobj.ltrim();
        return trimsobj.str;
    }

    测试

    console.log(trimsobj);
    var str = ',,n我们,,';
    var xx;
    xx = trim(str,',');
    document.write('--'+xx+'--');
    str = ',,天朗,,';
    xx = trim(str,',');
    document.write('--'+xx+'--');
    str = ',,左侧trim,,';
    xx = ltrim(str,',');
    document.write('--'+xx+'--');
    str = ',,右侧trim,,';
    xx = rtrim(str,',');
    document.write('--'+xx+'--');
    var str = '  n我们  ';
    var xx;
    xx = trim(str);
    document.write('--'+xx+'-- ');
    str = '  天朗  ';
    xx = trim(str);
    document.write('--'+xx+'-- ');
    str = '  左侧trim  ';
    xx = ltrim(str);
    document.write('--'+xx+'-- ');
    str = '  右侧trim  ';
    xx = rtrim(str);
    document.write('--'+xx+'-- ');
  • 相关阅读:
    telent

    linux系统下部署war包
    CentOS-7.0.中安装与配置Tomcat-7的方法
    ServletContextListener
    JAVA中静态块、静态变量加载顺序详解
    git 查看父分支
    Google Guice 之绑定1
    STM32 Cubemx 配置定时器定时1mS
    项目过程的几点经验总结
  • 原文地址:https://www.cnblogs.com/goldenstones/p/4860392.html
Copyright © 2011-2022 走看看