Sometimes we need to retrieve URL parameters values from browser address bar in our client side script to process some functioning like click to a button or show/hide some elements. Here I have created a function in JavaScript to get query string parameters from URL and displayed uses example.
Get query string parameters values from URL in JavaScript
Here is the function which will safely decode url components using regular expression. We can call this function and pass the query string parameter name as argument for which we wish to obtain value.
1 2 3 4 5 6 7 8 9 10 | <script type="text/javascript"> function getUrlParameter(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } var qsp = 'game', para = getUrlParameter(qsp); </script> |
Suppose we have the url as following:
http://example.com/sports?game=football
If we wish to retrieve the value for game
, we can pass it to qsp
variable as string and we will get football
as value. If the parameter doesn’t exist then the function would simply return empty string.
Hope this JavaScript function will help you to get values of query string parameters from URL. If you have any query or any jQuery/JavaScript issue then feel free to contact us.