I want to extract the plete path i.e the path followed by the host name of a URL in javascript.
var url = '.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 ,
I want to extract the plete 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 ,
Share Improve this question edited Mar 13, 2012 at 9:33 Achu asked Mar 13, 2012 at 8:56 AchuAchu 931 silver badge8 bronze badges 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 Commented Mar 13, 2012 at 9:02
- what is the "document.createElement('a')" method?, I have never heard of it before. – Ali Khalid Commented Mar 13, 2012 at 9:03
- Possible duplicate of Regular expression to remove hostname and port from URL? – stema Commented 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 Commented Mar 13, 2012 at 9:45
4 Answers
Reset to default 2If 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
^[^#]*?://.*?(/.*)$
Credit goes to strager:
Regular expression to remove hostname and port from URL?
How about using something tried and true: http://blog.stevenlevithan./archives/parseuri
There's even a demo: http://stevenlevithan./demo/parseuri/js/
and here is a much more specific regex for your question;
https?://[-A-Z0-9.]+(/[-A-Z0-9+&@#/%=~_|!:,.;?]*)?