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
5
  • You should be able to easily extract that form the pathname... :) Commented Nov 29, 2013 at 11:23
  • Just use: pathname.substr(pathname .lastIndexOf('/')) Commented Nov 29, 2013 at 11:24
  • "I'm currently on www.google.com/folder/folder/archive.php" I doubt that. example.com is reserved for exactly this reason :) Commented Nov 29, 2013 at 11:28
  • possible duplicate of How to extract the filename of URL in JavaScript? Commented Nov 29, 2013 at 11:34
  • Oh Gareth! I'll remember that for next time. :) Commented Nov 29, 2013 at 11:36

5 Answers 5

6

Try this :)

console.log(window.location.href.split('/').pop())
Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking this too, but what if I have a URL like: example.com/http ://google.com/otherPage.js how can I just split up the different parts?
or even example.com/index.php?page=http: //google.com
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]);

2 Comments

Thanks. If I were to just do console.log(a[-1]);, how come it says undefined in the console?
@Prateek: my solution is independent of the size of the URL. The objective was to achieve the last part of the URL.
0
alert("/"+window.location.pathname.split("/")[2] );

Comments

0

Try this

var path = "www.google.com/folder/folder/archive.php";
console.log(path.substring(path.lastIndexOf('/')+1));

Comments

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

Comments

Your Answer

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