0

I'm in need of a regular express that will parse 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.

0

5 Answers 5

2

Try this:

str = "www.mydomain.com/find_this/anything/anything"; 
path = /(?:http\:\/\/)?(?:www)?\.mydomain\.com\/([^\/]+)/.exec(str) [1]
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

I'm looking for regular express for a specific reason. No parsing.
@Atticus this is a clever answer, and you should show what you have tried.
looking for regular expression to use in .htaccess?
This is what I would do if I wasn't looking for a regular expression. Unfortunately the system my client uses examines an incoming link by regular expression.
0

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];

Comments

0

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.

Comments

0

Just try the following:

var rootDir = location.pathname.replace(/(^\/\w+\/).*/,"$1");

1 Comment

This works if you're needing the first directory from the current browser location.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.