什么是 URL 编码?
URL 编码(也称为百分号编码)是一种将 URL 中的特殊字符转换为 % 后跟两位十六进制数的格式。URL 只允许使用 ASCII 字母、数字和部分特殊字符,其他字符(如中文、空格)必须被编码。
URL 编码 vs URI 组件编码:
- URL 编码:使用 encodeURI(),保留 URL 结构字符(如 /、?、#、&),适合编码完整 URL
- URI 组件编码:使用 encodeURIComponent(),编码所有非字母数字字符,适合编码查询参数值
例如,空格在 URL 编码中变为 %20,中文 "你好" 变为 %E4%BD%A0%E5%A5%BD。
What is URL Encoding?
URL encoding (also known as percent-encoding) converts special characters in URLs into a format preceded by % followed by two hexadecimal digits. URLs only allow ASCII letters, digits, and a few special characters — all other characters (including Chinese characters and spaces) must be encoded.
URL Encode vs URI Component Encode:
- URL Encode — Uses
encodeURI(), preserves URL structure characters like /, ?, #, and &; suitable for encoding a full URL - URI Component Encode — Uses
encodeURIComponent(), encodes all non-alphanumeric characters; suitable for encoding query parameter values
For example, a space becomes %20, and the Chinese characters "你好" become %E4%BD%A0%E5%A5%BD.