读书人

String.prototype.replace(str,func)

发布时间: 2012-11-08 08:48:11 作者: rapoo

String.prototype.replace(str,func) 例中func的参数问题?

<div id="myDiv"></div>  <script>String.prototype.supplant = function(o){return this.replace(/{([^{}]*)}/g,function (a,b){var r = o[b];return typeof r==='string'?r:a;});};var template ='<table border="{border}">' +'<tr><th>Last</th><td>{last}</td></tr>' +'<tr><th>First</th><td>{first}</td></tr>'+'</table>';var data = {first:"Carl",last:"Hollywood",border:"2"};myDiv.innerHTML = template.supplant(data);  </script>


请问一下
function (a,b){var r = o[b];return typeof r==='string'?r:a;}

的a,b是怎样传过来的呢? 1 楼 boin 2008-02-27 a,b 是正则表达式捕获的子匹配

请搜索JS正则表达式相关的内容。 2 楼 falchion 2008-02-29 多谢了! 终于找到了

引用replace() 方法的参数 replacement 可以是函数而不是字符串。在这种情况下,每个匹配都调用该函数,它返回的字符串将作为替换文本使用。该函数的第一个参数是匹配模式的字符串。接下来的参数是与模式中的子表达式匹配的字符串,可以有 0 个或多个这样的参数。接下来的参数是一个整数,声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。

读书人网 >Web前端

热点推荐