Categories
AngularJS Career Code Area Java Script Tips and Tricks

Getting Query String Values Without a Hash in the URL

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation, hash bang URL format is: http://example.com/#!/bar?baz=23

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation,  hash bang URL format is:

http://example.com/#!/bar?baz=23

So if you have no hash bang in your URL (e.g. http://example.com/bar?baz=23), and try to get query string value, then you can use this snippet.

function getQueryParams(queryParam, url) 
{
        var pageUrl = url || window.location.search.substring(1);
        var urlVariables = pageUrl.split(/[&||?]/);
        var response = null;

        for (var i = 0; i < urlVariables.length; i += 1) {
            var param = urlVariables[i];
            var paramName = (param || '').split('=');

            if (paramName[0] === queryParam) {
                response = paramName[1];
            }
        }
        return response;
}
    
console.log(getQueryParams('baz', 'http://example.com/bar?baz=23'));

This code is also with pure JavaScript (withour AngularJS).

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

Your email address will not be published. Required fields are marked *