简体   繁体   中英

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/

I want to get the values after the # in JS .

Which are: articles and 123456

I was able to get the whole string using:

var type = window.location.hash.substr(1);

The result was: 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);
});

DEMO

Hope this helps.

Edit: or in a plain js function that you pass the url to.

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()

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

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