简体   繁体   中英

How to extract part of location.href in JavaScript?

In this example, what's the regexp to to extract 'first' from location.href, such as:

http://www.mydomain.com/first/

Perhaps not an answer to your question, but if you're writing in Javascript, you probably want to use location.pathname rather than extract it yourself from the entire href.

Since you asked for a regex solution, this would be it:

^(?:[^:]+://)?[^/]+/([^/]+)

This matches all of these variants (match group one would contain "first" in any case):

  • http://www.mydomain.com/first/
  • http://www.mydomain.com/first
  • https://www.mydomain.com/first/
  • https://www.mydomain.com/first
  • www.mydomain.com/first/ (this one and the next would be for convenience)
  • www.mydomain.com/first

To make it "http://"-only, it gets simpler:

^http://[^/]+/([^/]+)

you can use window.location.host and window.location.search just check out this page for details

var re = /^http:\/\/(www.)?mydomain\.com\/([^\/]*)\//;
var url = "http://mydomain.com/first/";

if(re.test(url)) {
  var matches = url.match(re);
  return matches[2]; // 0 contains whole URL, 1 contains optional "www", 2 contains last group
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM