zoukankan      html  css  js  c++  java
  • String.replace与String.format

      字符串的替换函数replace平常使用的频率非常高,format函数通常用来填补占位符。下面简单总结一下这两个函数的用法。

    一、String.replace的两种用法

      replace的用法如:replace(regexp, string|fn);第一个参数都是正则表达式,第二个参数可以是要替换的字符串,也可以是带返回值的函数,它的功能就是拿第二个参数替换匹配的值。

      1.replace(regexp, string):我想把“乐小天”中的“小”替换成“大”,如下所示。

    console.log("乐小天".replace(/小/g, "大"));//乐大天

    //trim的实现方式 console.log(" 乐小天 ".replace(/(^s+)|(s+$)/g, ""));//乐小天

      2.replace(regexp, fn);fn这个回调函数可以有四种参数,第一种参数是匹配regexp的字符串;第二种为匹配regexp子表达式的字符串(有几个自表达式,顺延对应几个参数,如果没有子表达式,则第二个参数为第三种参数);第三种参数为regexp匹配字符串在字符串中的索引;第四种参数为当前调用replace的字符串。

      拿上面trim的实现为例,它的正则表达式包含两个子表达式:(^s+)和(s+$);所以回调函数应该有5个参数。当然,如果没有子表达式,则只有三种参数。

    console.log("        乐小天    ".replace(/(^s+)|(s+$)/g, 
        function(match, matchChild1, matChild2, index, strObj){
            console.log("match:" + match + ";");
            console.log("matchChild1:" + matchChild1 + ";");
            console.log("matChild2:" + matChild2 + ";");
            console.log("index:" + index + ";");
            console.log("strObj:" + strObj + ";");
            return "";
        }
    ));
    /**
    match:        ;
    matchChild1:        ;
    matChild2:undefined;
    index:0;
    strObj:        乐小天    ;
    match:    ;
    matchChild1:undefined;
    matChild2:    ;
    index:11;
    strObj:        乐小天    ;
    乐小天
    */

    二、String.format的实现

      有的时候我们事先不知道字符串对应位置应该替换成什么,所以我们用占位符“{数字}”在字符串中进行预先占位,在真正确定的时候才将其替换掉。说白了就是将未知的替换字符封装成参数,让替换逻辑这个不变的部分与替换参数这个变化部分进行分离。

      1.format实现:

    //扩展format
    String.prototype.format = String.prototype.format || function() {
        var args = arguments;
        return this.replace(/{(d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };
    
    console.log("{0}是个{1}帅哥!".format('孙悟空', '大'));//孙悟空是个大帅哥!

      2.format替换字符在form校验中用到的比较多,比如前端UI框架MiniUI的校验对象VType是这么定义的:

    mini.VTypes = {
       minDateErrorText : "Date can not be less than {0}",
       maxDateErrorText : "Date can not be greater than {0}",
       ...  
    };

      在返回错误信息的时候将对应的边界值替换掉“{0}”

      

      

  • 相关阅读:
    Delphi XE2 之 FireMonkey 入门(13)
    Delphi XE2 之 FireMonkey 入门(12)
    Delphi XE2 之 FireMonkey 入门(11)
    svn泄漏敏感信息利用方式
    提取windows用户明文密码
    firefox中outlook.com页面卡顿的原因
    漏洞的定义
    Hydra--密码破解的神器
    数据库设计那些事(数据库范式)
    数据库范式
  • 原文地址:https://www.cnblogs.com/longhx/p/5478601.html
Copyright © 2011-2022 走看看