2016-08-19 32 views
-1

我試圖提取URL像這樣的最後一段的最後一段:獲取URL

localhost:15043/Maintenance/ModelDetails/3?makeId=14 

這:

//localhost:15043/Maintenance/ModelDetails/3 

我用下面的代碼,但是這個代碼不工作在此鏈接:

localhost:15043/Maintenance/ModelDetails/3?makeId=14 

var last_segment = window.location.hash.split('/').pop(); 
+0

你在下面的評論中指出'14'應該是結果。在提問時要花更多的時間來提供關於每種情況下的結果的清晰描述。在這一點上,這個問題很不明確。 – 2016-08-19 15:18:18

回答

3

您可以使用window.location的路徑,搜索和/或散列部做到這一點。因爲它只是用作運行此代碼的示例,所以請忽略解析器。

var url = "http://localhost:15043/Maintenance/ModelDetails/3?blah=abc&makeId=14#test"; 
 
function parseUrl(url) { 
 
    var a = document.createElement("a"); 
 
    a.href = url; 
 
    return a; 
 
} 
 
var parser = parseUrl(url); 
 
var last_segment = parser.pathname.split('/').pop(); 
 
var searchParams = parser.search.substring(1).split("&"); 
 
var lastParamValue = searchParams[searchParams.length-1].split("=")[1]; 
 
var hash = parser.hash; 
 

 
console.log(last_segment); 
 
console.log(lastParamValue); 
 
console.log(hash);

+1

是的,我已經在我的編輯中注意到了。 – 10100111001

+0

我想要得到14 –

+0

要使其輸出正確,您應該爲URL添加一個方案。至少在Firefox中,它爲路徑和搜索提供了空白結果。 – 2016-08-19 15:14:42

2

不會爲你這個簡單的正則表達式.+\/工作,replace()

var getLastSegment = function(url) { 
 
    return url.replace(/.+\//, ''); 
 
}; 
 

 
console.log(getLastSegment("localhost:15043/Maintenance/ModelDetails/3?makeId=14")); 
 

 
console.log(getLastSegment("//localhost:15043/Maintenance/ModelDetails/3"));

0

您可以在.split()方法使用正則表達式

const pattern1 = /\?|\/|\&/; 
const pattern2 = /\//; 
const str = 'localhost:15043/Maintenance/ModelDetails/3?makeId=14'; 

console.log(str.split(pattern1).pop()); // return 'makeId=14' 
console.log(str.split(pattern2).pop()); // return '3?makeId=14' 

pattern1將分裂的?/&字符的URL,pattern2只有/字符。所以你可以調整正則表達式來匹配你想要的。