---
title: "URL转码escape() encodeURI() encodeURIComponent()"
author: "J2EE大鸟"
date: "2012-12-24T15:16:07Z"
tags: []
categories: ["编程语言"]
slug: "url-escape-encodeuri-encodeuricomponent"
draft: false
lastmod: "2012-12-24T15:16:07Z"
id: 1753099
url: "https://benworld.iteye.com/blog/1753099"
---

转：http://deony2jacob1314.iteye.com/blog/1753068

js对文字进行编码涉及3个函数：escape,encodeURI,encodeURIComponent，相应3个解码函数：unescape,decodeURI,decodeURIComponent 

1.传递参数时需要使用encodeURIComponent，这样组合的url才不会被#等特殊字符截断。                              
例如:   
url:'/supervisorManage/supervisorInfoManage/dispatchSupervisorInfo.action?mode=add&supervisorName='+encodeURIComponent('监管人员')+'&population.populationType='+$("#\_populationType\_").val(); 

2、 encodeURI 着眼于对整个URL进行编码,进行url跳转时可以整体使用encodeURI   
例如：Location.href="/encodeURI"("http://cang.baidu.com/do/s?word=百度&ct=21"); 

3、 escape()不能直接用于URL编码，它的真正作用是返回一个字符的Unicode编码值   
   对 String 对象编码以便它们能在所有计算机上可读，     
    escape(charString)   
    必选项charstring参数是要编码的任意String对象或文字。     
   说明   
  escape方法返回一个包含了charstring内容的字符串值（Unicode格式）。所有空格、标点、重音符号以   
   及 其他非ASCII字符都用%xx编码代替，其中xx等于表示该字符的十六进制数。例如，空格返回的是 "%20 "   。   
字符值大于255的以%uxxxx格式存储。     
注意 :escape方法不能够用来对统一资源标示码(URI)进行编码。对其编码应使用encodeURI和encodeURIComponent 方法。 

最多使用的应为encodeURIComponent，它是将中文、韩文等特殊字符转换成utf-8格式的url编码，所以如果给后台传递参数需要使用encodeURIComponent时需要后台解码对utf-8支持（form中的编码方式和当前页面编码方式相同）   
escape不编码字符有69个：\*，+，-，.，/，@，\_，0-9，a-z，A-Z   
encodeURI不编码字符有82个：!，#，$，&，'，(，)，\*，+，,，-，.，/，:，;，=，?，@，\_，~，0-9，a-z，A-Z   
encodeURIComponent不编码字符有71个：!， '，(，)，\*，-，.，\_，~，0-9，a-z，A-Z