Thursday, June 13, 2013

Commenting out JavaScript regular expressions in Node.js

Weird oddity commenting out code

This line works fine:


hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);


However, if I try to comment out a block using /* */, things get wonky:

/*
hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);
*/

The JavaScript interpreter throws a nice syntax error.
It turns out that the JavaScript interpreter sees the /* and says "cool, its a comment. I'll go until I see it close." Then it sees the */ of the regular expression and says "ok, I'm done."
It is left with some seemingly bogus line:
,"path=/"+hostMap[pref]);
*/

Now, if you could make this appear to be legitimate, you could get some seriously obfuscated code going.

The workaround is to comment out the line with the // mechanism:

//hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);


Now if I could just figure out how to get chrome to start showing spell-check suggestions again...

No comments:

Post a Comment