首页
学习
活动
专区
工具
TVP
发布

encodeURI

encodeURI()  函数通过将特定字符的每个实例替换为一个、两个、三或四转义序列来对统一资源标识符 (URI) 进行编码 (该字符的 UTF-8 编码仅为四转义序列)由两个 "代理" 字符组成)。

语法

encodeURI(URI)

参数

URI一个完整的URI.

返回值

    一个新字符串, 表示提供的字符串编码为统一资源标识符 (URI)。

描述

不对保留字符进行编码。以下示例显示了URI“scheme”可能包含的所有部分。请注意某些字符是如何表示特殊含义的:

http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor

因此,encodeURI 不会编码制定完整URI所必需的字符。此外,encodeURI 不会编码一些额外的字符,称为“未保留标记”,这些字符没有保留的用途,但是可以在URI中“按原样”允许。(请参阅RFC2396)

encodeURI避免了所有字符,除了

Not Escaped:

    A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( )

encodeURI的区别encodeURIComponent如下:

var set1 = ";,/?:@&=+$";  // Reserved Characters
var set2 = "-_.!~*'()";   // Unreserved Marks
var set3 = "#";           // Number Sign
var set4 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // #
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

请注意,如果试图对不属于高-低对的surrogate进行编码,则会引发URIError,

// high-low pair ok
console.log(encodeURIComponent('\uD800\uDFFF'));

// lone high surrogate throws "URIError: malformed URI sequence"
console.log(encodeURIComponent('\uD800'));

// lone low surrogate throws "URIError: malformed URI sequence"
console.log(encodeURIComponent('\uDFFF')); 

Use

请注意,encodeURI本身不能形成正确的HTTP GET和POST请求,例如XMLHTTPRequests,因为“&”,“+”和“=”不被编码,在GET和POST请求中被视为特殊字符。encodeURIComponent可以编码这些字符。

请注意,URIError如果试图编码不属于高低位对的代理项,将会抛出一个错误,例如,

// high-low pair ok
console.log(encodeURI('\uD800\uDFFF'));

// lone high surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uD800'));

// lone low surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uDFFF')); 

还要注意的是,如果您希望遵循最近的RFC3986中的URL(保留了用于IPv6的方括号),并且在形成可能是URL(例如主机)的一部分的内容时不进行编码,则以下代码段可能有帮助:

function fixedEncodeURI(str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}

规范

Specification

Status

Comment

ECMAScript 3rd Edition (ECMA-262)

Standard

Initial definition.

ECMAScript 5.1 (ECMA-262)The definition of 'encodeURI' in that specification.

Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'encodeURI' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'encodeURI' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券