为什么匹配的子字符串在JavaScript中返回“undefined”?

时间:2022-06-08 20:21:16

I came across a strange behaviour when doing some regular expressions in JavaScript today (Firefox 3 on Windows Vista).

今天在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

There's nothing wrong with the regular expression. As you can see, it has matched the correct part in the first console.log call.

正则表达式没有任何问题。如您所见,它与第一个console.log调用中的正确部分匹配。

Internet Explorer 7 and Chrome both behave as expected: format[1] returns "%A" (well, Internet Explorer 7 doing something right was a bit unexpected...)

Internet Explorer 7和Chrome都按预期运行:format [1]返回“%A”(好吧,Internet Explorer 7做正确的事情有点出乎意料......)

Is this a bug in Firefox, or some "feature" I don't know about?

这是Firefox中的一个错误,还是一些我不知道的“功能”?

2 个解决方案

#1


15  

This is because console.log() works like printf(). The first argument to console.log() is actually a format string which may be followed with additional arguments. %A is a placeholder. For example:

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

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

See console.log() documentation for details. %A and any other undocumented placeholders seem to do the same as %o.

有关详细信息,请参阅console.log()文档。 %A和任何其他未记录的占位符似乎与%o相同。

#2


1  

Seems like %A somehow translates into the string undefined.

似乎%A以某种方式转换为字符串undefined。

Try escaping the %A part, I think that will solve the problem.

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

#1


15  

This is because console.log() works like printf(). The first argument to console.log() is actually a format string which may be followed with additional arguments. %A is a placeholder. For example:

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

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

See console.log() documentation for details. %A and any other undocumented placeholders seem to do the same as %o.

有关详细信息,请参阅console.log()文档。 %A和任何其他未记录的占位符似乎与%o相同。

#2


1  

Seems like %A somehow translates into the string undefined.

似乎%A以某种方式转换为字符串undefined。

Try escaping the %A part, I think that will solve the problem.

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