Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

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!
0
zumpoof
Asked:
zumpoof
  • 4
  • 2
1 Solution
 
b0lsc0ttCommented:
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
 
b0lsc0ttCommented:
Sorry there was a typo.

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

It could also be done as ...

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

bol
0
 
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
b0lsc0ttCommented:
Sure use ...

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

bol
0
 
zumpoofAuthor Commented:
Works like a charm! I just had to make a small modification:


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

Thanks b0lsc0tt
0
 
b0lsc0ttCommented:
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

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now