views:

327

answers:

2

I came across a strange behaviour when doing some regexes in Javascript today (Firefox 3 on Vista).

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 regex, as you can see it has matched the correct part in the first console.log call.

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

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

+1  A: 

Seems like %A somehow translates into the string undefined.

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

Yuval A
Good catch. It's treated as a URL escape (like %20 and the like) but then %A isn't one of those so gets to be undefined.
PEZ
Seems to be an issue with Firebug
PEZ
@PEZ: How about "user error?" ;)
Jonathan Lonowski
+10  A: 

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("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.

Rene Saarsoo
To be clear, this is not how console.log behaves in Safari's Web Inspector.
eyelidlessness