Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a matched substring returning "undefined" in JavaScript?

I came across a strange behaviour when doing some regular expressions in JavaScript today (Firefox 3 on Windows 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 regular expression. 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, Internet Explorer 7 doing something right was a bit unexpected...)

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

like image 766
nickf Avatar asked Jan 11 '09 12:01

nickf


2 Answers

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.

like image 67
Rene Saarsoo Avatar answered Oct 26 '22 05:10

Rene Saarsoo


Seems like %A somehow translates into the string undefined.

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

like image 27
Yuval Adam Avatar answered Oct 26 '22 04:10

Yuval Adam