📅  最后修改于: 2023-12-03 15:14:52.513000             🧑  作者: Mango
encodeURIComponent
The encodeURIComponent()
function is a built-in JavaScript function that encodes a string as a valid URI component by replacing certain characters with their escape sequences. This allows the string to be used in a URL as a query parameter without causing issues with special characters.
encodeURIComponent(URIcomponent)
The URIcomponent
parameter is the string that needs to be encoded.
const myString = 'Hello, World! How are you?';
console.log(encodeURIComponent(myString));
// Output: Hello%2C%20World%21%20How%20are%20you%3F
In this example, encodeURIComponent()
is used to encode the myString
variable. The output shows that the special characters ,
, !
and ?
have been replaced with their escape sequences %2C
, %21
and %3F
.
The encodeURIComponent() function encodes a string by replacing certain characters with their escape sequences. The characters that are replaced are determined by the following table:
| Character | Escape Sequence |
| --- | --- |
| ;
| %3B
|
| ,
| %2C
|
| /
| %2F
|
| ?
| %3F
|
| :
| %3A
|
| @
| %40
|
| &
| %26
|
| =
| %3D
|
| +
| %2B
|
| $
| %24
|
| #
| %23
|
| %
| %25
|
| "
| %22
|
| <
| %3C
|
| >
| %3E
|
| |
| %7C
|
encodeURIComponent()
encodes all characters except the following characters: A-Z
, a-z
, 0-9
, and -
, _
, .
, and ~
. These characters are considered "unreserved" and do not need to be encoded.
encodeURIComponent()
is a useful tool for encoding strings for use in URLs. It is important to use this function to avoid issues with special characters that could break a URL.