user1560022
user1560022

Reputation:

Get specific part of url of a link

I want to get a specific part of a url between the third and fourth slashes of a link on the page.

EDIT: Sorry I don't think I was clear the first time, I meant getting the specific part of the url OF A LINK found on the page.

Upvotes: 0

Views: 10410

Answers (4)

js-coder
js-coder

Reputation: 8336

var getSegment = function (url, index) {
   return url.replace(/^https?:\/\//, '').split('/')[index];
}

Usage:

getSegment("http://domain.com/a/b/c/d/e", 4); // "d" 

The replace makes sure that the first two slashes after the protocol (http or https) don't count.

Upvotes: 7

MrYo
MrYo

Reputation: 1817

you should elaborate you question and should specify which is your domain, that means on what purpose you are asking that question ??

This may help you:

var urlValue = url.split("/");

Then store urlValue as array. then pick up third and forth value of the urlvalue on array.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

I'd suggest:

var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html';

console.log(link.split('/')[5]);​

JS Fiddle demo.

The reason we're using [5] not [4] is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.

Upvotes: 0

Paul Fleming
Paul Fleming

Reputation: 24526

Here's a working example of getting a particular path segment.

Code:

var url = "www.test.com/one/two/three?p1=v&p2=v#anc";
var file = url.split('?')[0];
var pathanddomain = file.split('/');
var path = pathanddomain.splice(1, pathanddomain.length-1);
var pathIndexToGet = 2;
document.write(path[pathIndexToGet]);​

If you want to do this for the current page, use:

var url = window.location.href;

Also, if your url starts with http(s)://, you will need to remove this.

Upvotes: 2

Related Questions