Retrieving Escaped URL Parameters with JavaScript
Many developers encounter the challenge of extracting URL parameters that contain encoded characters. This can result in JavaScript errors due to malformed URI sequences. In this article, we'll explore a straightforward jQuery plugin and its modification to address this issue.
jQuery Plugin for URL Parameter Retrieval
The following jQuery plugin provides a convenient method for retrieving URL parameters, even those that are escaped:
$.getUrlParameter = function(name) { return decodeURI( (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); };
Usage:
var searchTerm = $.getUrlParameter('search');
Modification for Escaped Characters
To handle URL parameters with escaped characters, a simple modification to the plugin is required:
$.getUrlParameter = function(name) { return decodeURIComponent( (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); };
By utilizing the decodeURIComponent function, this modified plugin can decode any encoded characters in the URL parameter value.
Note: The original plugin decoded the retrieved parameter using decodeURI, which handles UTF-8 encoded characters. However, decodeURIComponent is more appropriate for URL parameters, as it can decode any encoded character.
The above is the detailed content of How Can I Retrieve Escaped URL Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!