1

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

4
  • 1
    Work for me. Check this Commented Jul 27, 2015 at 6:26
  • The query string has to be before the hash. The URL should be http://192.168.0.216:1009/main.html?id=123&name=test#!/video.html Commented Jul 27, 2015 at 6:31
  • @Barmar Probably OP uses some SPA framework where query string is emulated like this. Commented Jul 27, 2015 at 6:39
  • He probably need to URL-encode the # if it's intended to be part of the pathname. Commented Jul 27, 2015 at 6:39

1 Answer 1

2

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

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.