Wednesday

RegExs for Common JavaScript Bugs

I use these 2 quite a bit:

:\s*[\[{]\s*[\]}]
This catches empty object and array literals in another object literal. Chances are you put this in a class/prototype definition like so:

Class.create({
myHash: {},
myList: []
});

That's roughly equivalent to declaring 'myHash' and 'myList' as static in Java. Unless you really want every instance of that class to share the same hash/array, that initialization needs to happen in the constructor:

Class.create({
initialize: function() {
this.myHash = {};
this.myList = [];
}
});

,\s*[\]}]
Catches [1,2,] and {1,2,}. The trailing comma causes IE to fail silently, which is always fun to debug. Since this is always wrong, you can change that to ,(\s*[\]}]) and do a find and replace with $1 as the replacement.

Post another regex findable bug if you know one.

No comments: