比如讲到replace()方法的第二个参数也可以是一个函数。在只有一个匹配项(即与模式匹配的字符串)的情况下,会想这个函数传递3个参数:模式的匹配项、模式匹配项在字符串中的位置和原始字符串。这里面讲的与模式匹配的字符串是什么意思? 另外这个代码我也没怎么看懂,麻烦帮我捋一捋
function htmlEscape(text){ return text.replace(/[<>"&]/g, function(match, pos, originalText){
switch(match){
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
alert(htmlEscape("<p class=\"greeting\">Hello world!</p>")); //<p class="greeting">Hello world!</p>
当第二个参数也是一个函数的时候,这个函数相当于回调,它接受一个匹配,并且返回应该替换的文本。你把规则写好了作为参数传给replace