Home > Web Front-end > JS Tutorial > How Can I Retrieve Escaped URL Parameters in JavaScript?

How Can I Retrieve Escaped URL Parameters in JavaScript?

Susan Sarandon
Release: 2024-12-08 11:06:12
Original
125 people have browsed it

How Can I Retrieve Escaped URL Parameters in JavaScript?

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]
    );
};
Copy after login

Usage:

var searchTerm = $.getUrlParameter('search');
Copy after login

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]
    );
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template