user1469270
user1469270

Reputation:

Getting parts of a URL with JavaScript

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

Upvotes: 3

Views: 5258

Answers (5)

A J
A J

Reputation: 2140

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

Upvotes: 0

Midhun Krishna
Midhun Krishna

Reputation: 1759

Try this :)

console.log(window.location.href.split('/').pop())

Upvotes: 6

Prateek
Prateek

Reputation: 6965

Try this

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

Upvotes: 0

Uncle Aaroh
Uncle Aaroh

Reputation: 831

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]);

Upvotes: 4

Rituraj ratan
Rituraj ratan

Reputation: 10378

alert("/"+window.location.pathname.split("/")[2] );

Upvotes: 0

Related Questions