escape、encodeURI和encodeURIComponent的区别

506 阅读1分钟

总的来说escape是对字符串(string)进行编码,encodeURI和encodeURIComponent是对URL进行编码,作用是让它们在所有电脑上可读。

encodeURI与encodeURIComponent都可以对url进行编码,唯一区别就是编码的字符范围

encodeURI方法不会对下列字符编码 ASCII字母、数字、~!@#$&*()=:/,;?+'
encodeURIComponent方法不会对下列字符编码 ASCII字母、数字、~!*()'

基本使用

编码中文:
    var param = "中文"
    console.log(escape(param)) // %u4E2D%u6587
    console.log(encodeURI(param)) //%E4%B8%AD%E6%96%87
    console.log(encodeURIComponent(param)) //%E4%B8%AD%E6%96%87
    
编码url:
    var url = "http://localhost:85/Exam/settingAction_saveSettings.action?safeHatNumLength=测试"
    console.log(encodeURI(url))
    //http://localhost:85/Exam/settingAction_saveSettings.action?safeHatNumLength=%E6%B5%8B%E8%AF%95
    
    console.log(encodeURIComponent(url))
    //http%3A%2F%2Flocalhost%3A85%2FExam%2FsettingAction_saveSettings.action%3FsafeHatNumLength%3D%E6%B5%8B%E8%AF%95
    
1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape,而且这个方法一般不会用到。

2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。

3、当你需要编码URL中的参数的时候,那么encodeURIComponent是最好方法。