String.method('deentityify', function() {
    //字符映射表,它映射字符的名字到对应的字符
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };
    //返回deentityify方法
    return function() {
        //这才是deentityify方法。它调用字符串的replace方法,
        //查找'&'开头和';'结束的子字符串。如果这些字符可以在字符映射表中找到,
        //那么就将该字符替换为映射表中的值,它用到了一个正则表达式(参见第七章)
        return this.replace(/&([^&;]+);/g,
            function(a, b) {
                var r = entity[b];
                return typeof r === 'string' ? r : a;
            }
        );
    };
} ());function deentityifyTest() {
    return "&lt; &quot;&gt; ".deentityify(); //输出<”>
}这里,生成了个替换字符串的函数
function(a, b) {
                var r = entity[b];
                return typeof r === 'string' ? r : a;
            }
但参数a,b 是什么,怎么就执行了

解决方案 »

  1.   

    replace的第一个参数为正则,按照正则,字符串的某一部分匹配的时候,执行第二个function参数匹配到几次,则function执行几次一般说来这个function的参数可以有4个,分别记为a,b,c,d
    例子:
    var str = '<div id="{wo}" >{ni}</div>';
    str.replace(/\{([a-z]+)\}/ig, function(a, b, c, d) {
    alert(a);
    alert(b);
    alert(c);
    alert(d);
    });
    a:满足条件的字符串
    b:第一个参数中匹配到一个括号正则的字符串,如a匹配到的为{wo},{ni},那么b为wo,ni
    c:满足条件的字符串在原字符串中出现的位置
    d:原字符串
      

  2.   

    给String类添加'deentityify'方法,用于反编码"&lt; &quot;&gt;"。return this.replace(/&([^&;]+);/g,
                function(a, b) {
                    var r = entity[b];
                    return typeof r === 'string' ? r : a;
                }
            );参数a是正则表达式(/&([^&;]+);/g(匹配所有&开始和;结束的字符串)匹配到的内容,如:可匹配到&amp;或者&quot;等。
    参数b是正则表达式(/&([^&;]+);/g中括号中匹配的内容。如:a=&quot;,则b=quot
    这样,由
    var entity = {
            quot: '"',
            lt: '<',
            gt: '>'
        };

    r=entity["quot"]='"';
    同理
    r=entity["lt"]="<";
    r=entity["gt"]=">";