Internet Explorer’s Trailing Comma Woes
Internet Explorer is notorious for breaking on trailing commas in JavaScript array declaration. e.g.
var obj = {
a: 1,
b: 2,
};
fails on IE, while all other browsers just ignore the innocuous trailing comma after second element.
Weeding out these commas from JavaScript code is absolute PITA. However, here is a regular expression search string I wrote to search such instances in the code.
,\s*\n+\s*[\}\)\]]
Even better,
,\s*\n+(\s*\/\/.*\n)*\s*[\}\)\]]
matches multiple new lines and comments.
That’s actually an object literal, not an array.
I just came across your page because I’ve noticed that this script:
alert([1, 2, 3, ].length);
displays “4″ in IE 8, but “3″ in Firefox and Safari.
earwicker
March 3, 2010 at 9:00 pm
As o [1,2,3,].length and [1,2,3,,,,].length, I really do not know which behaviour is correct according to the spec.
In rhino i have this:
js> [1,2,3].length
3
js> [1,2,3,].length
3
js> [1,2,3,,].length
4
js> [1,2,3,,,].length
5
js> [1,2,3,,,,].length
3
js> [1,2,3,,,,,].length
3
js> [1,2,3,,,,,,].length
3
Very strange. VERY STRANGE.
witek
July 24, 2010 at 4:56 am
as earwicker said “That’s actually an object literal, not an array” … so this new change applies to object literals only. not to arrays. For arrays trailing comma is still illeagle
aaaaaa
June 6, 2013 at 8:42 pm
[...] fly in IE7, so remove the extra comma. If you need a way to do this in bulk, you could try regex. The corrected version looks like: <script type="text/javascript"> function [...]
Google maps API v3 not showing up in Internet Explorer 7 or 6 « Zephyr Dev
April 5, 2011 at 6:35 pm
Can you pls make me an easy example to use your regex to check a full external js code? Thanks in advance. ciao h.
haltman
May 2, 2011 at 4:48 pm
Nice, thanks for posting that.
Travis
September 17, 2012 at 3:40 pm
To use this regexp in command line, do the following:
find -name ‘*.js’ -exec grep -Pzl “,\s*\n+(\s*\/\/.*\n)*\s*[\}\)\]]” {} \;
drachenfels
November 28, 2012 at 6:13 pm