You can retrieve any query string value based on parameter name from the url of current page. Following JavaScript function returns the value for given parameter name. These are raw JavaScript codes, so you don’t need to use jQuery.
Method 1 :
function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexString = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexString); var found = regex.exec(window.location.search); if(found == null) return ""; else return decodeURIComponent(found[1].replace(/\+/g, " ")); }
Your url parameters may be url-encoded and you want to get decoded value, this function return decoded value. There are an alternative way to write this function. Following function do the same work like above function. You may use following codes instead.
Method 2 :
function getParameterByName(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null; }
When your given parameter name is not exists in the url then this function returns null instead of ‘null’.
Using jQuery
I found two jQuery plugins to get url parameter value
To learn more critical points to play with URL query string parameters you may go to following discussion pages.
Reference 1 , Reference 2
This function returns the answer of following queries
- JavaScript to read a URL query string
- Getting Query String Parameters with JavaScript
- Javascript to get Query String from URL in raw JavaScript
- Get URL and URL Parts in JavaScript
- Get Current Page QueryString Using JavaScript
- JavaScript Function to Get URL Query Values
- Raw JavaScript and URL parameters
- JavaScript to Read GET variables from URL
Permalink
You shouldn’t use regex for this as it will fail in some scenarios.
You’d better off using a tiny reusable module like:
https://github.com/sindresorhus/query-string