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

encodeURIComponent

encodeURIComponent()是对统一资源标识符(URI)的组成部分进行编码的方法。它使用一到四个转义序列来表示字符串中的每个字符的UTF-8编码(只有由两个Unicode代理区字符组成的字符才用四个转义字符编码)。

语法

encodeURIComponent(str);

参数

strString. URI 的组成部分。

返回值

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

描述

encodeURIComponent转义所有字符,除了:

Not Escaped:

    A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURIComponent区别encodeURI如下:

var set1 = ";,/?:@&=+$";  // Reserved Characters
var set2 = "-_.!~*'()";   // Unescaped Characters
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)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

注意,如果试图编码一个非高-低位完整的代理字符,将会抛出一个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')); 

使用encodeURIComponent从POST'd服务器形式的用户输入的字段。这将编码“&”符号,这些符号可能会在数据输入过程中为特殊HTML实体或其他需要编码/解码的字符而无意中生成。

例如,如果用户写入“Jack&Jill”,则文本可以被编码为“Jack&Jill”。如果没有encodeURIComponent和 “” 符号,可能会在服务器上解释为新字段的开始,并危及数据的完整性。

对于application/x-www-form-urlencoded(POST) 这种数据方式,空格需要被替换成 '+',所以通常使用encodeURIComponent的时候还会把 "%20" 替换为 "+"。

为了更严格的遵循 RFC 3986(它保留 !, ', (, ), 和 *),即使这些字符并没有正式划定 URI 的用途,下面这种方式是比较安全的:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

示例

下面这个例子提供了 UTF-8 下Content-DispositionLink的服务器响应头信息的参数(例如 UTF-8 文件名):

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" 
             + encodeRFC5987ValueChars(fileName);

console.log(header); 
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars(str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            // so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

// here is an alternative to the above function
function encodeRFC5987ValueChars2(str) {
  return encodeURIComponent(str).
    // Note that although RFC3986 reserves "!", RFC5987 does not,
    // so we do not need to escape it
    replace(/['()*]/g, c => "%" + c.charCodeAt(0).toString(16)). // i.e., %27 %28 %29 %2A
    // The following are not required for percent-encoding per RFC5987,
    // so we can allow for a little better readability over the wire: |`^
    replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16)));
}

规范

Specification

Status

Comment

ECMAScript 3rd Edition (ECMA-262)

Standard

Initial definition.

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

Standard

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

Standard

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

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

(Yes)

(Yes)

(Yes)

5.5

(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)

扫码关注腾讯云开发者

领取腾讯云代金券