我尝试将函数作为替换方法的第二个参数传递,但仅在不使用大括号的情况下起作用?!
function reg1(match,amount,unit){
amount=Number(amount)-1;
if(amount==1){
unit=unit.slice(0,unit.length-1)
}
else if(amount==0){
amount="no"
}
return amount+" "+unit
}
undefined
"1 lemon,2 cabbages and 103 eggs".replace(/(\d+) (\w+)/g,reg1())
"NaN undefined,NaN undefined and NaN undefined"
"1 lemon,2 cabbages and 103 eggs".replace(/(\d+) (\w+)/g,reg1)
"no lemon,1 cabbage and 102 eggs"