Retireving the Current URL
The current page URL can be accessed directly through the native window object:
window.location.href;
This requires no external libraries—standard JavaScript suffices.
Extracting URL Query Parameters
Retrieving specific parameters from the URL query string involves parsing the search portion. The following approach uses a regular expression pattern to match and extract parameter values.
function getQueryParam(paramName) {
var pattern = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
var result = window.location.search.substring(1).match(pattern);
if (result !== null) {
return decodeURIComponent(result[2]);
}
return null;
}
For a URL like http://example.com/page?redirect=dashboard, retrieve the value like this:
var target = getQueryParam('redirect');
Creating a jQuery Plugin Method
Extend jQuery by adding a custom method that wraps the parameter extraction logic:
(function ($) {
$.getQueryParam = function (paramName) {
var pattern = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
var result = window.location.search.substring(1).match(pattern);
if (result !== null) {
return decodeURIComponent(result[2]);
}
return null;
};
})(jQuery);
After adding this extension, retrieve parameters using the jQuery syntax:
var target = $.getQueryParam('redirect');
Complete Implementation Example
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Extend jQuery with custom method
(function ($) {
$.getQueryParam = function (paramName) {
var pattern = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
var result = window.location.search.substring(1).match(pattern);
if (result !== null) {
return decodeURIComponent(result[2]);
}
return null;
};
})(jQuery);
// Extract parameter using jQuery
var target = $.getQueryParam('redirect');
console.log(target);
});
</script>
Handling Character Encoding
When working with non-ASCII characters in URL paarmeters, encoding and decoding methods must match. If parameters are encoded using encodeURI(), decoding must use decodeURIComponent():
| Encoding Method | Decoding Method |
|---|---|
escape() |
unescape() |
encodeURI() |
decodeURI() |
encodeURIComponent() |
decodeURIComponent() |
Using mismatched encode/decode methods produces garbled text, particularly with Chinese characters.
Alternative Parsing Approach
Another method builds an object containing all query parameters:
function parseQueryString() {
var params = {};
var query = window.location.search.substring(1);
var pairs = query.split('&');
for (var i = 0; i < pairs.length; i++) {
var separator = pairs[i].indexOf('=');
if (separator === -1) continue;
var key = pairs[i].substring(0, separator);
var value = pairs[i].substring(separator + 1);
params[key] = decodeURIComponent(value);
}
return params;
}
var allParams = parseQueryString();
var id = allParams['id'];
This approach collects all parameters into a single object, useful when multiple values need access.