Achu
Achu

Reputation: 93

Regular expression for getting pathname of a url

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 ,

Upvotes: 3

Views: 2307

Answers (4)

WhoSayIn
WhoSayIn

Reputation: 4719

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

https?://[-A-Z0-9.]+(/[-A-Z0-9+&@#/%=~_|!:,.;?]*)?

Upvotes: 1

mplungjan
mplungjan

Reputation: 178421

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

Upvotes: 2

deviousdodo
deviousdodo

Reputation: 9172

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

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

Upvotes: 1

Marcelo Mason
Marcelo Mason

Reputation: 7070

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

Credit goes to strager:

Regular expression to remove hostname and port from URL?

Upvotes: 2

Related Questions