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
Susan SarandonOriginal
2024-12-08 11:06:12186browse

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

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!

Statement:
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
Previous article:My React Journey: Day 9Next article:My React Journey: Day 9