Crawlicious

tools for web business

javascript regex confusion

| 0 comments

I had some confusion today with javascript and regular expressions. It was really a dumb mistake because it turned out to be an incorrectly escaped dot (.). Basically I was trying to detect something that had a literal dot in it.  I had escaped the literal dot, but it was being seen by the regex engine as a dot wildcard.  Part of the confusion was that in the string form of a regular expression you need to escape with 2 backslashes and in the perl/slash form you escape with 1 backslash.

To demonstrate I will put up some alerts that you can run in your error console in FF, or throw on a page.  My goal below is to show true when we find the string “test.it”.  You will see that the (.) needs double escaping in string object syntax and needs single escaping in perl syntax.


// using perl type syntax
alert("is match? " + /test\\.it/.test('testXitok')); // => is match? false  (extra escape problem masked, it will hurt us later)
alert("is match? " + /test\\.it/.test('test.itok')); // => is match? false (should have been true!!!! extra escape got us!)
alert("is match? " + /test\.it/.test('testXitok')); // => is match? false (correct with single escape)
alert("is match? " + /test\.it/.test('test.itok')); // => is match? true (correct with single escape)

// using string object method syntax
alert("is match? " + (null != "testXitok".match("test\\.it"))); // => is match? false (correct with double escape)
alert("is match? " + (null != "test.itok".match("test\\.it"))); // => is match? true (correct with double escape)
alert("is match? " + (null != "testXitok".match("test\.it"))); // => is match? true (single escape got us here!  It hurts!)
alert("is match? " + (null != "test.itok".match("test\.it"))); // => is match? true (single escape problem is masked)

Moral of the story, go read the stinking book.  It is such a temptation to be a javascript hacker instead of doing it right.  Well, no more time to hack at javascript, I gotta move on to the next project!

Eric

Leave a Reply