JavaScript转义
1. encodeURI()
encodeURI()
函数通过将特定字符替换为转义序列来对统一资源标识符 (URI) 进行编码 。
encodeURI
会替换所有的字符,但不包括以下字符,即使它们具有适当的UTF-8转义序列:
类型 | 包含 |
---|---|
保留字符 | ; , / ? : @ & = + $ |
非转义的字符 | 字母 数字 - _ . ! ~ * ' ( ) |
数字符号 | # |
完整URI:
http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
示例:
encodeURI("https://cn.bing.com/search?q=你好")
// "https://cn.bing.com/search?q=%E4%BD%A0%E5%A5%BD"
1.1 注意
encodeURI
自身无法产生能适用于HTTP GET 或 POST 请求的URI,例如对于 XMLHTTPRequests, 因为 “&”, “+”, 和 “=” 不会被编码,然而在 GET 和 POST 请求中它们是特殊字符。然而encodeURIComponent
这个方法会对这些字符编码。- 如果试图编码一个非高-低位完整的代理字符,将会抛出一个
URIError
错误,例如:
// 编码高-低位完整字符 ok
console.log(encodeURI('\uD800\uDFFF'));
// 编码单独的高位字符抛出 "Uncaught URIError: malformed URI sequence"
console.log(encodeURI('\uD800'));
// 编码单独的低位字符抛出 "Uncaught URIError: URI malformed"
console.log(encodeURI('\uDFFF'));
- 如果URL需要遵循较新的RFC3986标准,那么方括号是被保留的(给IPv6),因此对于那些没有被编码的URL部分(例如主机),可以使用下面的代码:
function fixedEncodeURI (str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
2. decodeURI()
**decodeURI()**
函数能解码由encodeURI
创建或其它流程得到的统一资源标识符(URI)。
decodeURI("https://cn.bing.com/search?q=%E4%BD%A0%E5%A5%BD");
// "https://cn.bing.com/search?q=你好"
3. encodeURIComponent()
encodeURIComponent()
函数通过将UTF-8编码的转义序列替换为某些字符的编码 URI
encodeURIComponent
转义除了如下所示外的所有字符