簡體   English   中英

獲取鏈接網址的特定部分

[英]Get specific part of url of a link

我想獲取頁面鏈接的第三和第四斜杠之間的URL的特定部分。

編輯:對不起,我認為我不是第一次不清楚,我的意思是獲取頁面上找到的鏈接URL的特定部分。

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

用法:

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

replace可確保協議( httphttps )后的前兩個斜杠不計數。

是獲取特定路徑段的有效示例。

碼:

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

如果要對當前頁面執行此操作,請使用:

var url = window.location.href;

另外,如果您的網址以http(s)://開頭,則需要將其刪除。

您應該詳細說明您的問題,並應指定哪個域,這意味着您出於什么目的提出該問題?

這可以幫助您:

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

然后將urlValue存儲為數組。 然后在數組上選取urlvalue的第三和第四值。

我建議:

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

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

JS小提琴演示

之所以使用[5]而不是[4]是因為URL開頭的兩個斜杠,以及JavaScript數組是基於零的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM