3

I'm currently on www.google.com/folder/folder/archive.php and using window.location to determine that. I actually want to target /archive.php, and nothing else.

Is there something that could achieve that?

window.location.host = "www.google.com"

window.location.pathname = "folder/folder/archive.php"

???? = "/archive.php
  • You should be able to easily extract that form the pathname... :) – techfoobar Nov 29 '13 at 11:23
  • Just use: pathname.substr(pathname .lastIndexOf('/')) – Andrew Nov 29 '13 at 11:24
  • "I'm currently on `www.google.com/folder/folder/archive.php`" I doubt that. [`example.com`](http://tools.ietf.org/html/rfc2606) is reserved for exactly this reason :) – Gareth Nov 29 '13 at 11:28
  • possible duplicate of [How to extract the filename of URL in JavaScript?](http://stackoverflow.com/questions/6543242/how-to-extract-the-filename-of-url-in-javascript) – Felix Kling Nov 29 '13 at 11:34
  • Oh Gareth! I'll remember that for next time. :) –  Nov 29 '13 at 11:36

5 Answers5

6

Try this :)

console.log(window.location.href.split('/').pop())
MIdhun Krishna
  • 1,739
  • 1
  • 13
  • 31
4

You need to split the array and get the last portion. You can do it like this

var a = window.location.pathname.split("/");
console.log(a[a.length - 1]);
Zeeshan Abbas
  • 821
  • 6
  • 20
  • Thanks. If I were to just do `console.log(a[-1]);`, how come it says `undefined` in the console? –  Nov 29 '13 at 11:40
  • @Prateek: my solution is independent of the size of the URL. The objective was to achieve the last part of the URL. – Zeeshan Abbas Nov 29 '13 at 11:46
0
alert("/"+window.location.pathname.split("/")[2] );
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
0

Try this

var path = "www.google.com/folder/folder/archive.php";
console.log(path.substring(path.lastIndexOf('/')+1));
Prateek
  • 6,785
  • 2
  • 24
  • 37
0

This will select part from the last '/'.

var last =

window.location.toString().substr(window.location.toString().lastIndexOf('/'));

last will always be the path no matter which ever page you run this script.

eg: http://www.example.com/../../../../../test.html

The output will be test.html

http:// - Protocol
www - Server-Name (subdomain)
example - Second Level Domain (SLD)
com - Top Level Domain (TLD)
/test.html - Path
mplungjan
  • 169,008
  • 28
  • 173
  • 236
A J
  • 2,112
  • 15
  • 24