[英]How to get values of multiple URL variables after the hash sign
假設我有這個網址:
http://www.example.com/#articles/123456/
我想在JS
獲取#
之后的值。
分別是: 文章和123456
我能夠使用以下命令獲取整個字符串:
var type = window.location.hash.substr(1);
結果是: articles / 123456 /
有沒有辦法單獨獲取每個變量?
提前致謝。
我認為這是您要尋找的東西。
$('#btn').on('click', function(){
var url = 'http://www.example.com/#articles/123456/';
var bitAfterHash = url.split('#').pop();
var parts = bitAfterHash.split('/');
var firstPart = parts[0];
var lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
$('p').html(firstPart + ' : ' + lastPart);
});
希望這可以幫助。
編輯:或在傳遞網址的普通js函數中。
function getUrlParts(url){
var bitAfterHash = url.split('#').pop();
var parts = bitAfterHash.split('/');
var firstPart = parts[0];
var lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
document.getElementById('text').innerHTML= firstPart + ' : ' + lastPart;
};
var type = window.location.hash.substr(1);
var parts = type.split("/");
console.log(parts[0]) // -> articles
console.log(parts[1]) // -> 123456
var url = "http://www.example.com/#articles/123456/";
var lastIndex = lastIndex = url.endsWith("/") ? url.length-1: url.length;
var hashIndexPlusOne = url.lastIndexOf('#') + 1;
var startIndex = url[hashIndexPlusOne]==="/" ? hashIndexPlusOne + 1 : hashIndexPlusOne;
values = url.substring(startIndex , lastIndex).split("/");
//Result:
//values[0] = articles, values[1]= 123456
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.