Regular Expression to parse term out of URL
I'm in need of a regular express that will par开发者_JS百科se the first directory of a URL:
www.mydomain.com/find_this/anything/anything..
So -- I wasn't sure how to structure a regex to grab the string containing that first directory, any help appreciated.
Edit -- parsing is not an option, I am trying to create a regular expression.
Try this:
str = "www.mydomain.com/find_this/anything/anything";
path = /(?:http\:\/\/)?(?:www)?\.mydomain\.com\/([^\/]+)/.exec(str) [1]
You can just do:
var myString = "www.mydomain.com/find_this/anything/blah"
var string_I_want = myString.replace(/\/\//g, "").split("/")[1]
Much easier to read.
The stuff matched by the first capturing group (raw regex):
^(?:https?://)?(?:\w+)(\.\w+)*(?:\:\d+)/([^/]+)
Matches optional http://
/https://
, webserver/ip/port, then, the first group is what you want.
var url = 'www.mydomain.com/find_this/anything/anything';
var match = /^(?:https?:\/\/)?(?:\w+)(\.\w+)*(?:\:\d+)\/([^\/]+)/.exec(url);
var root = match[1];
Here are some options:
With capture:
/(.*?)/
With named capture:
/(?<first_directory>.*?)/
With protocol and capture:
(?:https?://.*?)?/(.*?)/
With protocol and named capture:
(?:https?://.*?)?/(?<first_directory>.*?)/
You'll just need to translate for your flavor.
Just try the following:
var rootDir = location.pathname.replace(/(^\/\w+\/).*/,"$1");
精彩评论