JavaScript regex to extract a path from a URL

I need a JavaScript regex that extracts the path out of a URL.  For example:

For:
'www.foo.com/my/page_123' or 'bar.com/my/page_123'

I'd need '/my/page_123'

Thanks!
zumpoofAsked:
Who is Participating?
 
b0lsc0ttConnect With a Mentor IT ManagerCommented:
Sure use ...

str = str.match(/http://.+?(\/.+)/)[1]

bol
0
 
b0lsc0ttIT ManagerCommented:
If you have to use a regex then use ...

str = str.match((\/.+)/)[1]

Let me know how this works or if you have a question.  This does assume the URL isn't in other text that might have a forward slash before the first one in the URL.

bol
0
 
b0lsc0ttIT ManagerCommented:
Sorry there was a typo.

str = str.match(/(\/.+)/)[1]

It could also be done as ...

str = str.match(/\/.+/)

bol
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
zumpoofAuthor Commented:
b0lsc0tt,

Sorry, I thought location.href wouldn't include the 'http://'.  Could you adapt it to support:

'http://www.foo.com/my/page_123' or 'http://bar.com/my/page_123'

Again, sorry for the mixup.
0
 
zumpoofAuthor Commented:
Works like a charm! I just had to make a small modification:


str = str.match(/http:\/\/.+?(\/.+)/)[1]

Thanks b0lsc0tt
0
 
b0lsc0ttIT ManagerCommented:
Your welcome!  Thanks for catching that.  Sorry!  I'm glad you got it so quick.  It is almost the end of a LONG day and a long week so I am a little slow.  :)

Thanks for a fun question, the grade and the points.

bol
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.