HTTP URL编码和解码

StoneLee 发布于 文章字数: 207 阅读次数:

HTTP URL编码和解码

注释:ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。

encodeURI() + decodeURI()

decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。

示例:
<script type="text/javascript">

    var test1="http://www.w3school.com.cn/My+ first++/"

    //编码
    document.write(encodeURI(test1)+ "<br />")

    //解码
    document.write(decodeURI(test1))

</script>

编码结果:http://www.w3school.com.cn/My+%20first++/
解码结果:http://www.w3school.com.cn/My+ first++/

encodeURIComponent() + decodeURIComponent()

decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码

示例:

<script type="text/javascript">

    var test1="http://www.w3school.com.cn/My+ first++/"

    //编码
    document.write(encodeURIComponent(test1)+ "<br />")

    //解码
    document.write(decodeURIComponent(test1))

</script>

编码结果:http%3A%2F%2Fwww.w3school.com.cn%2FMy%2B%20first%2F
解码结果:http://www.w3school.com.cn/My+ first/