我今天在JavaScript中使用正则表达式时遇到了一种奇怪的行为(Windows Vista上的Firefox 3)。
var str = "format_%A";
var format = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(str);
console.log(format); // ["format_%A", "%A"]
console.log(format[0]); // "format_undefined"
console.log(format[1]); // Undefined
正则表达式没有错。如您所见,它与第一个console.log
调用中的正确部分相匹配。
Internet Explorer 7和Chrome的行为与预期一致:format[1]
返回“%A”(好吧,Internet Explorer 7做正确的事情有点出乎意料......)
这是Firefox中的一个错误,还是我不知道的一些“功能”?
答案 0 :(得分:16)
这是因为console.log()的工作方式与printf()类似。 console.log()的第一个参数实际上是一个格式字符串,可以跟随其他参数。 %A是占位符。例如:
console.log("My name is %A", "John"); // My name is "John"
有关详细信息,请参阅console.log() documentation。 %A和任何其他未记录的占位符似乎与%o。
相同答案 1 :(得分:1)
似乎%A
转换为字符串undefined
。
尝试转义%A
部分,我认为这样可以解决问题。