3

I want to extract the complete path i.e the path followed by the host name of a URL in javascript.

var url = 'https://domain.us/file.php/fghfgh?id=1'

Here i want to extract /file.php/fghfgh?id=1

How can this achieve only using regular expression not by "document.createElement('a')" methode ?

I need the answer in regular expression ,

4
  • Does the url always end with .us ?? Maybe you could just simply use the string.split(".us") --- This returns an array where array[1] holds the url part you want.
    – w00
    Mar 13, 2012 at 9:02
  • what is the "document.createElement('a')" method?, I have never heard of it before.
    – Ali Khalid
    Mar 13, 2012 at 9:03
  • Possible duplicate of Regular expression to remove hostname and port from URL?
    – stema
    Mar 13, 2012 at 9:34
  • the above one is just an example .I want to extract the string (include pathname + searchname) after the hostname of any url .Need answer in regular expression
    – Achu
    Mar 13, 2012 at 9:45

4 Answers 4

2

If you are accessing the location object, you could do

var path = location.href.replace(location.protocol+"//"+location.hostname,"")

or

var path = location.pathname+location.search

If you have # you may need to add it too as pointed out by just_mad:

var path = location.pathname+location.search+location.hash

0
2
^[^#]*?://.*?(/.*)$

Credit goes to strager:

Regular expression to remove hostname and port from URL?

1

How about using something tried and true: http://blog.stevenlevithan.com/archives/parseuri

There's even a demo: http://stevenlevithan.com/demo/parseuri/js/

1

and here is a much more specific regex for your question;

https?://[-A-Z0-9.]+(/[-A-Z0-9+&@#/%=~_|!:,.;?]*)?
3
  • i've checked with a regex tester and it worked. can you be more specific about the problem?
    – WhoSayIn
    Mar 13, 2012 at 14:28
  • i don't know regular expression very well . I tested like this way var url = 'suntimes.com/csp/cms/sites/STM/assets/js/jquery-latest.js' var path = url.match(/https?://[-A-Z0-9.]+(/[-A-Z0-9+&@#/%=~_|!:,.;?]*)?/); alert(path)
    – Achu
    Mar 14, 2012 at 4:51
  • but i couldn't get path as /csp/cms/sites/STM/assets/js/jquery-latest.js
    – Achu
    Mar 14, 2012 at 4:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.