How to end a regex using a slash in Javascript

Problem

I am trying to map the hash of a url using Javascript. The hash will be in the format

/#\/(.*)\// 

This is easy to achieve with the โ€œnew RegExp () methodโ€ to create a JS regular expression, but I canโ€™t figure out how to do this using the standard format, because the two slashes at the end start the comment, is there a way to write this so as not to start a comment?

Example

 // works myRegexp = new RegExp ('#\/(.*)\/'); // fails myRegexp = /#\/(.*)\// 
+7
javascript regex
source share
2 answers

I am trying to map the hash of a url using Javascript.

Yes, do not do this. Every browser has the perfect URL parser built in. Set href for the location object ( window.location or link), and you can read / write URLs from the 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 put the / -separated path in the hash code, I suggest hash.split('/') follow.

Regarding regex, both versions work the same for me. The final // does not cause a comment. If you just want to calm some dodgy syntax highlighting, you can potentially avoid / before \x2F .

+10
source share

This is not the beginning of the comment, like two lines in a line. See here: http://jsfiddle.net/Gr2qb/2/

+2
source share

All Articles