Rajeev Kumar
Rajeev Kumar

Reputation: 4963

Get query string from url in javascript

I have been trying fetching the query string from url using javascript.

I am using following code

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function() {
    prodId = getParameterByName('id');
    prodName = getParameterByName('name');
});

It works well for URL like http://my_ip/main.html?id=123&name=test

But when URL is like http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test it fails, giving empty string for prodID and prodName

Upvotes: 1

Views: 363

Answers (1)

dfsq
dfsq

Reputation: 193301

The problem is that http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test doesn't have location.search part. It has location.hash - everything after # character.

The simple thing you can do is to modify the function to be able to work with location.hash too. For example like this:

function getParameterByName(name, useHash) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location[useHash ? 'hash' : 'search']);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

and then use it like this:

var prodId = getParameterByName('id', true); // true - use location.hash for "query parameters"

Upvotes: 2

Related Questions