Javascript string traversing
Lately I needed to parse format that Cisco uses for specifying transfer masks and route patterns to an array of telephone numbers a user could choose from. I wrote a neat javascript function that traverses the string and does what needed. I even wrote a neat recursive function that displayed the numbers in HTML select field.
All worked fine. Until someone decided to test the thing on VM running Windows XP SP3 with IE 8.0.6001.18702 . The thing crashed. Not only that, it also displayed a nice little pop-up claiming that Javascript is running slow. We all know that really means you have an infinite loop somewhere in JS code. Thing is, I ran the code numerous times on my PC, which runs Windows XP SP3 and IE 8.0.6001.18702 as well. The only difference that my PC is not a virtual machine. And it worked without a glitch. So I tested it to death in VMs IE and eventually located the problem.
Remember how you traversed a string in C? Typically you wrote something like this (and yes, I know I probably should have used a pointer):
char pszString[100] = "My silly string\0"; for (int i=0; i<strlen(pszString); i++) { char ch = pszString[i]; //do something spiffy }
As far as I remember, I use that all the time in JavaScript as well. I never had any issues. Guess what? In IE on VM that was the cause of my problems. So, all I had to do was:
var pszString = new String("My silly string"); for (int i=0; i<strlen(pszString); i++) { char ch = pszString.substr(i, 1); //do something spiffy }
And the stuff magically started to work.
Leave a Reply