I was reading Douglas Crockford's web page, JavaScript: The World's Most Misunderstood Programming Language, and I couldn't help but notice that, under Design Errors, he mentions "the notation for literal regular expressions." What exactly is he talking about? What's wrong with JavaScript's notation for regular expressions, and why?
+3
A:
Might have to do with the fact that it enforces you to escape /
characters, perhaps he wanted a more unique character to use as the notation.
/test//
is invalid, while /test\//
is a valid regex.
Whereas in some languages you can actually specify the denotion character in a string, eg:
$regex = '#test/#';
Where #
symbols do the denotion.
meder
2010-06-20 06:39:33
Very true, that's probably it. But what languages, besides PHP, actually let you specify the character? I have a hard time thinking of any, but that might just be because I hardly ever use regular expressions.
musicfreak
2010-06-20 07:12:14
Yeah. Crockford's complaint was about 'overloading' the slash character, but I think his main concern was about the overloading in JS in general (I think!). For example, if you comment out blocks of code with `/*...*/` you can see what would happen if you tried to comment out `/0x[0-9a-f]*/.test(strMyString);` with that. There've been a bunch of times that I've had to use the RegExp() method of creating regular expressions because the literals were prone to errors.
Andrew
2010-06-20 07:45:15
@Andrew Really? I see how it's possible, but I've never encountered that.
Justin Johnson
2010-06-20 08:36:02
@Justin It's unlikely you'd run into that problem in real life very often, particularly if your IDE supports JS syntax highlighting. But I have run into that specific problem a couple of times and it was a real head-scratcher. Comment out all the JS on a page in notepad and see it die on working code you'd not touched in weeks. "Wha...? But that's not the problem. And it's ALL BEEN COMMENTED OUT!!" It's also guaranteed to happen to you if you embed some large, minimized JS framework (like jQuery) into your site's code base and then comment it out (e.g. to see how it loads without jQuery). Fun.
Andrew
2010-06-20 09:57:18
@musicfreak The ["stream editor" sed](http://en.wikipedia.org/wiki/Sed) performs substitutions based on regular expressions, and lets you choose the delimiting symbol for substitutions.
Christian Semrau
2010-06-20 10:32:10