While Firefox blissfully ignores that extra comma, IE and Chrome treat it as if there's a null element after it which can cause problems that are difficult to debug. After many iterations, I came up with the following substitution:var myObject = { foo: 'foo', bar: 'bar', //baz: 'baz' };
To decode: It detects any comma that does not follow a // on the same line, and searches for a closing ] or } with any amount of whitespace or comments inbetween. It's not ridiculously fast but it gets the job done. This operates on a string that contains the whole file, line breaks and all. It's not perfect... it sometimes detects false positives (for instance, the character class \w,) and it may also behave strangely on strings containing anything comment-like. That's why I wrote a detection script that can be run before the one that fixes it. I've uploaded my code to a SourceForge project: https://sourceforge.net/projects/jscommas/s#^((?:[^/\n]|/(?!/))*),((?:\s*|//.*$|/\*(?:[^*]|\*(?!/))*\*/)*\s*[}\] +])#$1$2#mg
In reply to Detecting Dangling Commas in JavaScript by wink
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |