Monday, December 15, 2008

name.replace is not a function - jquery bug

While trying to implement RSH (Really Simple History, check out my how to implement RSH - Really Simple History and solve ajax history back button problem article for details), I got this dreaded "name.replace is not a function" error! It really drove me nuts as many seem to have got it reported it to the jquery team but for whatever reason jquery bugtracker has almost always marked it as resolved or moved to subcategories. That might all be right but the problem is that this error is still there and seems to emerge right from the jquery core file! I mean it's alright that jquery team has found it to be an invalid bug or resolved issue or relating strictly to jquery plugins (instead of jquery core) but when I see "name.replace is not a function" popping up in my webpage I have to do something to fix it, lol! And I can't do squat because on tracing back, I realize that "name.replace is not a function" is originating from the jquery core file!

So what to do? I personally did the following -

1) Do whatever needs to be done and make sure that the desired functionality is still maintained. That is, isolate the error producing code such that your functionality is not impacted by the error.

2a) Either change the browser settings to not show the error if you have less than 10 users who can't really tell a browser from a pumpkin pie.

2b) If you have some user base and most importantly if it's an internet application then do this thing that is both next best and next worst to the above approach! ;) Yeah, trap the silly "name.replace is not a function" error in a try catch block. This is bad because you've just hidden some error beyond redemption but the thing is that if you've done step 1 correctly then it doesn't matter all that much. So I just went ahead and did it. Below are steps to how to do it -

a) Search for name=name.replace in jquery-1.2.6.min.js file (or the not-minified version and your version number replaces 1.2.6 obviously).

b) Ignore the name=name.replace that has ""float";" before "name=name.replace" part. Yeah, there are two of the name=name.replace thingees.

c) add a try block before name and close it with a catch block just before the immediate "if" statement.

So initially it was like this -

opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]

And after our little change, it looks like -

opacity=([^)]*)/)[1])/100)+'':"";}try{name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});}catch(e){}if(set)elem[name]

Bingo! The stupid name.replace has finally decided to be a function now! The error is gone and if you've been struggling to "somehow" make it work before you can hit the clubs tonight then you are free to do so! Yeah, do it before some new yet unknown error pops out!

No comments:

Post a Comment