Home >Web Front-end >JS Tutorial >Escape, encodeURI, or encodeURIComponent: When to Use Which 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.
The escape() function should not be used, as it has been deprecated in the ECMAScript specification. It encodes all special characters except @, _, *, , and -.
Use encodeURI() when you need a functional URL. It encodes all characters except those specifically reserved for URLs. These reserved characters include /, &, ?, :, and @.
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
You would use encodeURI() to obtain the following encoded URL:
http://www.example.org/a%20file%20with%20spaces.html
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")
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 + "¶m2=99"
This will result in the following complete encoded URL:
http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99
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!