user1234
user1234

Reputation: 3159

How to find the indexOf the first paramater in the URL.Javascript

I have a url: '#tests/12345678/lists' and Im looking to return only the value of the 'id' here which is '12345678'. i tried:

getIdLocation = $(location).attr("href"); userid = getIdLocation.substring(getIdLocation.lastIndexOf("/") + 1);

that returns users, but m looking to return on the value of the id from the url? any ideas how can I achieve this? Thanks!

Upvotes: 1

Views: 60

Answers (2)

dave
dave

Reputation: 64667

This works similarily to the other answer, but checks a bit more to make sure it matches the expected format:

function getUserIdFromUrl(callback) {
    var id_from_url_regex = new RegExp(/(#tests\/|\/lists)/)
    var parts = $(location).attr("href").split(id_from_url_regex);
    var user_id = false;
    if (parts.length == 5 && parts[2] === parseInt(parts[2]).toString()) {
        user_id = parts[2];
    }
    if (false !== user_id) {
        if (typeof callback == 'undefined') {
          return user_id;
        } else {
            return callback(user_id);
        }
    } else {
        throw "Could not parse id from url";
    }
}

try {
    getUserIdFromUrl(function(user_id) { alert(user_id); });
} catch(e) {
    alert('it failed');
}

Upvotes: 0

Claudio Bredfeldt
Claudio Bredfeldt

Reputation: 1422

var getIdLocation = $(location).attr("href").hash;     
var parts = getIdLocation.split('/');
var userid = parts[1];

Upvotes: 1

Related Questions