2012-03-14 41 views
0

鉴于此Javascript:如何在Javascript正则表达式中分组?

String.method('deentityify', function() { 
    // The entity table. It maps entity names to 
    // characters. 
    var entity = { 
     quot: '"', 
     lt: '<', 
     gt: '>' 
    }; 

    // Return the deentityify method 
    return function() { 

     return this.replace(/&([^&;]+);/g, 
      function (a, b) { 
       var r = entity[b]; 
       return typeof r === 'string' ? r : a; 
      } 
     ); 
    }; 
}()); 

document.writeln('&lt;&quot;&gt;'.deentityify()); 

什么进入最后一个函数A和B,为什么?

我得知我们正在将我传入的字符串分成3组,但我不明白为什么&lt;正在进入一个为什么只有lt正在进入b。

+2

看一看的[MDN文档】(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)。 – 2012-03-14 17:17:19

回答

2

第一个参数包含整个匹配,所有连续的参数都是匹配的组。最后两个参数是偏移量和完整输入字符串。

var input = '&lt;&quot;&gt;' 
input.replace(/&([^&;]+);/g, function (a, b) 

模式的& +每non-& + ;所有出现的匹配。

a  b 
&lt; lt 
&quot; quot 
&gt; gt 

参见:MDN: String.replace with a function

+0

那么,第一场比赛是<对不对? lt从哪里来?对不起 - 我知道我很密集。 – 2012-03-14 17:19:08

+1

'lt'都是'&'和';'之间的非&'字符。它是由parens捕获的。 – 2012-03-14 17:20:12

+0

Argh。我仍然没有得到它。我不明白为什么我们每场比赛都传球两次。在我看来,我们只匹配3件事:< " >我们真的捕获6件事吗? – 2012-03-14 17:25:27