为什么$ 1 ... $ 9属性(RegExp)不适用于IE10?

问题描述:

我有一个旧的脚本,它曾经与IE一起工作,但我不知道为什么它只用IE10工作,任何人都有一些线索呢?

String.Format = function (a) { 
    var b = Array.prototype.slice.call(arguments, 1); 
    return a.replace(/{(\d+)}/g, function() { return b[RegExp.$1] }); 
}; 

根据MDN,不推荐使用RegExp.$n属性。

试试这个:

return a.replace(/{(\d+)}/g, function (match) { 
    // match will include the {} so we strip all non-digits 
    return b[match.replace(/\D/g, '')]; 
}); 

或者使用第一个括号匹配,以避免额外的replace电话:

return a.replace(/{(\d+)}/g, function (match, p1) { 
    return b[p1]; 
}); 

Source

Working example

+0

+1 - 更加完整。我撤回我的提交:) –

+0

耶,谢谢!我懒得弄清楚自己。只有一个观察,我们必须使用第二个参数发送到此脚本的作用函数。 – Cleiton

+0

@Cleiton我不确定你的意思是第二个参数到动作函数。看到我的工作示例进行演示。 – jbabey