Home > Web Front-end > JS Tutorial > Escape, encodeURI, or encodeURIComponent: When to Use Which for Query String Encoding?

Escape, encodeURI, or encodeURIComponent: When to Use Which for Query String Encoding?

Barbara Streisand
Release: 2024-12-11 02:12:09
Original
267 people have browsed it

Escape, encodeURI, or encodeURIComponent: When to Use Which for Query String Encoding?

When to Use Escape, encodeURI, or encodeURIComponent for Query String Encoding

In the context of sending a query string to a web server, the appropriate encoding method depends on the specific encoding requirements.

escape()

The escape() function should not be used, as it has been deprecated in the ECMAScript specification. It encodes all special characters except @, _, *, , and -.

encodeURI()

Use encodeURI() when you need a functional URL. It encodes all characters except those specifically reserved for URLs. These reserved characters include /, &, ?, :, and @.

encodeURIComponent()

Use encodeURIComponent() when you want to encode the value of a URL parameter. It encodes all characters except those explicitly specified as unreserved. These unreserved characters include /, ?, :, and @.

Example:

To encode the following query string:

http://www.example.org/a file with spaces.html
Copy after login

You would use encodeURI() to obtain the following encoded URL:

http://www.example.org/a%20file%20with%20spaces.html
Copy after login

However, if you want to encode the value of a parameter within the query string, you would use encodeURIComponent():

var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
Copy after login

The resulting encoded parameter value can then be appended to the base URL to form the complete URL:

var url = "http://example.net/?param1=" + p1 + "&param2=99"
Copy after login

This will result in the following complete encoded URL:

http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99
Copy after login

It's important to note that encodeURIComponent() does not encode the ' character, which can lead to security vulnerabilities if not handled properly when constructing HTML attributes.

The above is the detailed content of Escape, encodeURI, or encodeURIComponent: When to Use Which for Query String Encoding?. 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