views:

92

answers:

2

Problem

I am trying to match the hash part of a URL using Javascript. The hash will have the format

/#\/(.*)\//

This is easy to achieve using "new RegExp()" method of creating a JS regular expression, but I can't figure out how to do it using the standard format, because the two forward slashes at the end begin a comment. Is there another way to write this that won't start a comment?

Example

// works
myRegexp = new RegExp ('#\/(.*)\/');

// fails
myRegexp = /#\/(.*)\//
+1  A: 

It is not starting a comment, just like two slashes in a string. Look here: http://jsfiddle.net/Gr2qb/2/

pepkin88
+3  A: 

I am trying to match the hash part of a URL using Javascript.

Yeah, don't do that. There's a perfectly good URL parser built into every browser. Set an href on a location object (window.location or a link) and you can read/write URL parts from properties hostname, pathname, search, hash etc.

var a= document.createElement('a');
a.href= 'http://www.example.com/foo#bar#bar';
alert(a.hash); // #bar#bar

If you're putting a path-like /-separated list in the hash, I'd suggest hash.split('/') to follow.

As for the regex, both versions work identically for me. The trailing // does not cause a comment. If you just want to appease some dodgy syntax highlighting, you could potentially escape the / to \x2F.

bobince
Oh, nice -- I'll use that. Thanks!
lonesomeday