• JS encodeURI和encodeURIComponent


    一、最常用的encodeURI和encodeURIComponent

    对URL编码是常见的事,所以这两个方法应该是实际中要特别注意的。
    它们都是编码URL,唯一区别就是编码的字符范围,其中
    encodeURI方法不会对下列字符编码 ASCII字母 数字 ~!@#$&*()=:/,;?+'
    encodeURIComponent方法不会对下列字符编码 ASCII字母 数字 ~!*()'
    所以encodeURIComponent比encodeURI编码的范围更大。
    实际例子来说,encodeURIComponent会把 http:// 编码成 http%3A%2F%2F 而encodeURI却不会。

    二、最重要的,什么场合应该用什么方法

    1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。
    2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。
    比如
    encodeURI("http://www.cnblogs.com/season-huang/some other thing");
    编码后会变为
    "http://www.cnblogs.com/season-huang/some%20other%20thing";

    其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为

    "http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"

    看到了区别吗,连 "/" 都被编码了,整个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%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"
    看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。
  • 相关阅读:
    nodejs中处理回调函数的异常
    Web前端开发十日谈
    Android 高仿微信6.0主界面 带你玩转切换图标变色
    Android EventBus源码解析 带你深入理解EventBus
    Android EventBus实战 没听过你就out了
    究竟谁在绑架中国的4G政策?
    Android 实战美女拼图游戏 你能坚持到第几关
    oracle学习
    his使用-重置密码
    oracle中的DDL、DML、DCL
  • 原文地址:https://www.cnblogs.com/zrp2013/p/5145825.html
Copyright © 2020-2023  润新知