Reputation: 1494
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.
Upvotes: 0
Views: 2194
Reputation: 53
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.
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;
};
Upvotes: 2
Reputation: 21911
var type = window.location.hash.substr(1);
var parts = type.split("/");
console.log(parts[0]) // -> articles
console.log(parts[1]) // -> 123456
Upvotes: 2
Reputation: 744
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
Upvotes: 1