Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end a regular expression with a forward slash in Javascript

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 = /#\/(.*)\//
like image 952
lonesomeday Avatar asked Sep 15 '10 13:09

lonesomeday


People also ask

How do I specify a forward slash in regex?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.

How do you do a forward slash in JavaScript?

As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\). Also, to replace all the forward slashes on the string, the global modifier (g) is used.

How do you end a regular expression?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


1 Answers

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.

like image 102
bobince Avatar answered Oct 17 '22 05:10

bobince