[英]How to get values of multiple URL variables after the hash sign
Let's say i have this URL: 假设我有这个网址:
http://www.example.com/#articles/123456/ http://www.example.com/#articles/123456/
I want to get the values after the #
in JS
. 我想在
JS
获取#
之后的值。
Which are: articles and 123456 分别是: 文章和123456
I was able to get the whole string using: 我能够使用以下命令获取整个字符串:
var type = window.location.hash.substr(1);
The result was: articles/123456/ 结果是: articles / 123456 /
Is there a way to get each variable alone ? 有没有办法单独获取每个变量?
Thanks in advance. 提前致谢。
I think this is the sort of thing your looking for. 我认为这是您要寻找的东西。
$('#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);
});
Hope this helps. 希望这可以帮助。
Edit: or in a plain js function that you pass the url to. 编辑:或在传递网址的普通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;
};
Use String.prototype.split()
使用
String.prototype.split()
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.