encodeURI(String)主要用于整个URI(例如,http://www.jxbh.cn/illegal value.htm),而encodeURIComponent(String)主要用于对URI中的某一段(例如前面URI中的value.htm)进行编码。它们的主要区别在于,encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而encodeURIComponent()则会对它发现的任何非标准字符进行编码。来看下面的例子:
<script type="text/javascript"> var test1="http://www.wljcz.com/My first/"; var nn=encodeURI(test1); var now=decodeURI(test1); document.write(nn+ "<br />"); document.write(now); var test1="http://www.wljcz.com/My first/"; var bb=encodeURIComponent(test1); var nnow=decodeURIComponent(bb); document.write(bb+ "<br />"); document.write(nnow); </script>
其运行结果为:
http://www.wljcz.com/My%20first/
http://www.wljcz.com/My first/
http%3A%2F%2Fwww.wljcz.com%2FMy%20first%2F
http://www.wljcz.com/My first/