讲这3个方法区别的文章太多了,但是大部分写的都很绕。本文试图从实践角度去讲这3个方法。
简单来说,escape是对字符串(string)进行编码(而另外两种是对URL),作用是让它们在所有电脑上可读。 编码之后的效果是%XX或者%uXXXX这种形式。 其中 ASCII字母、数字、@*/+ ,这几个字符不会被编码,其余的都会。 最关键的是,当你需要对URL编码时,请忘记这个方法,这个方法是针对字符串使用的,不适用于URL。 事实上,这个方法我还没有在实际工作中用到过,所以就不多讲了。
其中,空格被编码成了 。但是如果你用了encodeURIComponent,那么结果变为
"http://www.cnblogs.com/season-huang/some other thing"看到了区别吗,连 "/" 都被编码了,整个URL已经没法用了。
3、当你需要编码URL中的参数的时候,那么encodeURIComponent是最好方法。
var param = "http://www.cnblogs.com/season-huang/"; //param为参数 param = encodeURIComponent(param); var url = "http://www.cnblogs.com?next=" + param; console.log(url) //"http://www.cnblogs.com?next=http://www.cnblogs.com/season-huang/" 看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。encodeURIComponent()相比encodeURI()要更加彻底。
例如:
<html> <body> <script type="text/javascript"> var test1="http://www.haorooms.com/My first/"; var nn=encodeURI(test1);进行编码 var now=decodeURI(test1);解析回来 var test1="http://www.haorooms.com/My first/"; var bb=encodeURIComponent(test1);进行编码 var nnow=decodeURIComponent(bb);解析回来 </script> </body> </html>输出结果是:
http://www.haorooms.com/My first/ http://www.haorooms.com/My first/ http%3A%2F%2Fwww.haorooms.com%2FMy%20first%2F http://www.haorooms.com/My first/