2009-01-11 77 views
4

今天在JavaScript中使用一些正则表达式时(Firefox 3在Windows   Vista上),我遇到了一个奇怪的行为。为什么匹配的子字符串在JavaScript中返回“undefined”?

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中这是个Bug,或者我不知道的一些“功能”?

+0

我从来没有见过你在这里使用的文字匹配语法。你能指出一些可以阅读的网页资源吗? – PEZ 2009-01-11 12:34:45

+0

我认为至少应该提供一个与以前几乎相同的问题的链接:http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a- javascript-regex – 2009-01-11 12:57:02

+0

@PEZ:你在说什么文字匹配语法? – nickf 2009-01-11 14:12:47

回答

15

这是因为console.log()的工作方式与printf()类似。 console.log()的第一个参数实际上是一个格式字符串,可以附加其他参数。 %A是一个占位符。例如:

console.log("My name is %A", "John"); // My name is "John" 

有关详细信息,请参见console.log() documentation。 %A和其他任何未公开的占位符似乎都与%o相同。

1

好像%A似乎翻译成字符串undefined

尝试转义%A部分,我认为这将解决问题。

相关问题