【定义+用法+区别+使用场景】escape(),encodeURI(),encodeURIComponent()

2022年6月10日14:49:56

一、escape

escape是对字符串进行编码

作用:让它们在所有电脑上可读

\color{#ea4335}{已废弃}: 该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。

废弃的 escape() 方法生成新的由十六进制转义序列替换的字符串. 使用 encodeURI 或 encodeURIComponent 代替.

二、encodeURI

encodeURI() 函数通过将特定字符的每个实例替换为一个、两个、三或四转义序列来对统一资源标识符 (URI) 进行编码

encodeURI 会替换所有的字符,但不包括以下字符,即使它们具有适当的UTF-8转义序列:

类型 包含
保留字符 ; , / ? : @ & = + $
非转义的字符 字母 数字 - _ . ! ~ * ’ ( )
数字符号 #

三、encodeURIComponent

encodeURIComponent()函数通过将一个,两个,三个或四个表示字符的UTF-8编码的转义序列替换某些字符的每个实例来编码 URI(二者定义基本相同)

encodeURI 会替换所有的字符,但不包括以下字符,即使它们具有适当的UTF-8转义序列:

类型 包含
非转义的字符 字母 数字 - _ . ! ~ * ’ ( )

所以encodeURIComponent比encodeURI编码的范围更大。

四、encodeURI和encodeURIComponent的不同点

var set1 = ";,/?:@&=+$";  // 保留字符
var set2 = "-_.!~*'()";   // 不转义字符
var set3 = "#";           // 数字标志
var set4 = "ABC abc 123"; // 字母数字字符和空格

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)

从上述代码可以看出,与encodeURI相比,encodeURIComponent会对保留字符和数字标志进行转义

五、使用场合

  1. 假定一个URI是完整的URI,那么使用

    e

    n

    c

    o

    d

    e

    U

    R

    I

    \color{#ea4335}{encodeURI}encodeURI对无需对那些保留的并且在URI中有特殊意思的字符进行编码。

  2. 在GET和POST请求中,使用

    e

    n

    c

    o

    d

    e

    U

    R

    I

    C

    o

    m

    p

    o

    n

    e

    n

    t

    \color{#ea4335}{encodeURIComponent}encodeURIComponent这个方法会对这些字符编码

必要性:为了避免服务器收到不可预知的请求,对任何用户输入的作为URI部分的内容你都需要用encodeURIComponent进行转义。

原因:
假如一个用户输入了"abc&time=123"作为填入comment变量的一部分,若不使用encodeURIComponent进行转义,服务器将得到的是component=abc&time=123。此时服务器得到两个键值对,因此出现参数错误,故在对用户输入的内容进行转义时,必须使用encodeURIComponent()函数

参考链接:

  • 作者:GPNU_Log
  • 原文链接:https://blog.csdn.net/ahLOG/article/details/120027218
    更新时间:2022年6月10日14:49:56 ,共 1967 字。