This function is much more complicated than it needs to be, but we'll fix it later.  I don't know if you are familiar with regular expressions, but they are much faster in JavaScript and it this whole function can be one line of code.