Get Query String using only JavaScript

Sending Query String URLs

lets assume we will have a link with a user’s id as a query string using ? to indicate the query string, id as a parameter name and =5842 to assign the value to the parameter:

<a href=”mypage.com/index.htm?id=5842“> Username </a>

Note: you can send multiple parameters using & as a seperator, example:

?id=5842&username=user1&password=psd

Loading Query String Values:

<script>

var urlParameters;

var UserID

//retrieving query string parameters
(window.onpopstate = function () {

var queryStringMatch,
regexReplaceSymbols = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decodeURI = function (s) { return decodeURIComponent(s.replace(regexReplaceSymbols¬†, ” “)); },
queryString = window.location.search.substring(1);

urlParameters = {};
while (queryStringMatch= search.exec(queryString))
urlParameters[decodeURI(queryStringMatch[1])] = decodeURI(queryStringMatch[2]);

})();

//checking if parameter id exists and if it contains any value

if (urlParameters[“id”] != null && (urlParameters[“id”] != “”)){

UserID = urlParameters[“id”]; //assigning the parameters value to UserID

doSomething();

}

function doSomething()

{

//You can use UserID here now which contains the user’s id read from the query string

}

</script>