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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Detecting Dangling Commas in JavaScript
by MidLifeXis (Monsignor) on Oct 27, 2010 at 21:43 UTC | |
by wink (Scribe) on Nov 01, 2010 at 18:11 UTC | |
|
Re: Detecting Dangling Commas in JavaScript
by Anonymous Monk on Oct 27, 2010 at 19:12 UTC | |
by wink (Scribe) on Oct 27, 2010 at 19:14 UTC | |
|
Re: Detecting Dangling Commas in JavaScript
by LanX (Saint) on Oct 28, 2010 at 19:14 UTC | |
|
Re: Detecting Dangling Commas in JavaScript
by choroba (Cardinal) on Oct 28, 2010 at 13:25 UTC | |
by wink (Scribe) on Oct 28, 2010 at 14:44 UTC | |
|
Re: Detecting Dangling Commas in JavaScript
by bellaire (Hermit) on Jan 20, 2011 at 18:26 UTC |