简体   繁体   中英

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM