5

let say that in our websites we can have urls like:

http://domainame.com/dir/one-simple-name.html
https://dmainame.com/mail/send.php
https://dmainame.com/mail/read

etc..

So i would like to retrieve

dir/one-simple-name
mail/send
mail/read

Whats the best way to achieve it?

Toni Michel Caubet
  • 18,208
  • 50
  • 194
  • 356
  • 1
    possible duplicate of [How do I parse a URL into hostname and path in javascript?](http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – Brad Feb 07 '12 at 17:05
  • @Brad that answer returns the extension again – Toni Michel Caubet Feb 07 '12 at 17:15
  • If that answer doesn't meet your needs, try one of the 50 other duplicates, or ask on how to split a string by `.`. – Brad Feb 07 '12 at 17:17

4 Answers4

15

Everybody stand back! I know regular expressions! Try this one:

var my_location = window.location.toString().match(/\/\/[^\/]+\/([^\.]+)/)[1];
iblue
  • 27,950
  • 18
  • 84
  • 126
4

I would recommend doing this by,

var url = "https://www.somegoodwebsite.com/happy/ending/results/index.html";
console.log(url.replace(/^.*\/\/[^\/]+/, '') ); 

;

Result:
happy/ending/results/index.html
Lee Taylor
  • 7,155
  • 14
  • 29
  • 44
Sanjay Pradeep
  • 379
  • 3
  • 6
4

You can use this:

var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);

In javascript, you can access the various parts of the URL via the window.location object.

window.location.href - the entire URL 
window.location.host - the hostname and port number - [www.sample.com]:80
window.location.hostname - the hostname - www.sample.com
window.location.pathname - just the path part - /search
window.location.search - the part of the URL after the ? symbol - ?q=demo

In your case, you can use window.location.pathname and then if you need to strip the file extension off the filename, you can do that with some additional javascript:

var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);

This line of javascript will get the pathname component of the URL and then replace any file extension with "" (effectively removing it) and the remove the leading slash.

jfriend00
  • 637,040
  • 88
  • 896
  • 906
  • a = "http://stackoverflow.com/questions/9180511/remove-protocol-domainame-domain-and-file-extension-from-url" "http://stackoverflow.com/questions/9180511/remove-protocol-domainame-domain-and-file-extension-from-url" a.replace(/\.[^\.\/]+$/, "").substr(1); "ttp://stackoverflow.com/questions/9180511/remove-protocol-domainame-domain-and-file-extension-from-url" – Sheik797 Apr 25 '15 at 05:05
0

A more jqueryish way than using just regular expressions:

var path = $('<a>', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'')
CodeJoust
  • 3,690
  • 20
  • 23