0

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.

1

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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;
};

2 Comments

Where you've found an indication for the presence of jQuery?
@Andreas I've edited my answer to include a plain js function for it. :)
1
    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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.