美文网首页
encodeURI() 和 encodeURIComponent

encodeURI() 和 encodeURIComponent

作者: 砂壶 | 来源:发表于2020-02-26 22:34 被阅读0次

    区别

    encodeURIComponent()是对统一资源标识符(URI)的组成部分进行编码的方法。而encodeURI操作的是完整的URI。

    • encodeURIComponent()对字符进行编码,除了:
      A-Z a-z 0-9 - _ . ! ~ * ' ( )

    • encodeURI()对字符进行编码,除了:
      A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    • 可以看出encodeURI不处理编码的字符比encodeURIComponent多: ; , / ? : @ & = + $ #

    示例

    var diffset = ";,/?:@&=+$";  
    var sameset = "A-Za-z0-9-_.!~*'()";   
    var url = "https://www.baidu.com/a b c"; 
    
    console.log(encodeURI(diffset)); // ;,/?:@&=+$
    console.log(encodeURI(sameset)); // A-Za-z0-9-_.!~*'()
    console.log(encodeURI(url));  // https://www.baidu.com/a%20b%20c
    
    console.log(encodeURIComponent(diffset)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
    console.log(encodeURIComponent(sameset)); // A-Za-z0-9-_.!~*'()
    console.log(encodeURIComponent(url)); // https%3A%2F%2Fwww.baidu.com%2Fa%20b%20c
    

    使用情景

    比如进行get请求时携带参数key=value,多个参数是用&对键值进行分割,当value值内本身就含有&时解析出来的键值对可能出现问题,需要用encodeURIComponent()进行编码。而当将访问的url存在空格等不允许的字符时,要对整个url进行编码则使用encodeURI()。


    escape()不作比较,该特性已经从 Web标准中删除。

    参考资料及延伸:

    相关文章

      网友评论

          本文标题:encodeURI() 和 encodeURIComponent

          本文链接:https://www.haomeiwen.com/subject/temgchtx.html