• URL对象 js


    URL对象

    内建的 URL 类提供了用于创建和解析 URL 的便捷接口.
    语法:new URL(url, [base]);
    url —— 完整的 URL,或者仅路径(如果设置了 base),
    base —— 可选的 base URL:如果设置了此参数,且参数 url 只有路径,则会根据这个 base 生成 URL。
    例如

    let url1 = new URL('https://javascript.info/profile/admin');
    let url2 = new URL('/profile/admin', 'https://javascript.info');
    
    alert(url1); // https://javascript.info/profile/admin
    alert(url2); // https://javascript.info/profile/admin
    

    searchParams

    处理url参数问题
    包括:

    • append(name, value) —— 按照 name 添加参数,
    • delete(name) —— 按照 name 移除参数,
    • get(name) —— 按照 name 获取参数,
    • getAll(name) —— 获取相同 name 的所有参数(这是可行的,例如 ?user=John&user=Pete),
    • has(name) —— 按照 name 检查参数是否存在,
    • set(name, value) —— set/replace 参数
      例子:
    let url = new URL('https://google.com/search');
    
    url.searchParams.set('q', 'test me!'); // 添加带有一个空格和一个 ! 的参数
    
    alert(url); // https://google.com/search?q=test+me%21
    
    url.searchParams.set('tbs', 'qdr:y'); // 添加带有一个冒号 : 的参数
    
    // 参数会被自动编码
    alert(url); // https://google.com/search?q=test+me%21&tbs=qdr%3Ay
    
    // 遍历搜索参数(被解码)
    for(let [name, value] of url.searchParams) {
      alert(`${name}=${value}`); // q=test me!,然后是 tbs=qdr:y
    }
    

    编码字符串

    1.encodeURI —— 编码整个 URL
    encodeURI 会替换所有的字符,但不包括以下字符

    2.decodeURI —— 解码为编码前的状态。
    3.encodeURIComponent —— 编码 URL 组件,例如搜索参数,或者 hash,或者 pathname。
    encodeURIComponent 转义除了如下所示外的所有字符

    4.decodeURIComponent —— 解码为编码前的状态

    encodeURIComponent() 和 encodeURI 有以下几个不同点

    主要是encodeURIComponent的转义范围更广,除了不转义字符,其他的全部转义

    var set1 = ";,/?:@&=+$";  // 保留字符
    var set2 = "-_.!~*'()";   // 不转义字符
    var set3 = "#";           // 数字标志
    var set4 = "ABC abc 123"; // 字母数字字符和空格
    
    console.log(encodeURI(set1)); // ;,/?:@&=+$
    console.log(encodeURI(set2)); // -_.!~*'()
    console.log(encodeURI(set3)); // #
    console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
    
    console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
    console.log(encodeURIComponent(set2)); // -_.!~*'()
    console.log(encodeURIComponent(set3)); // %23
    console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
    
  • 相关阅读:
    cocos2d-x 2.2 study ------------------------ 双击事件(转)
    cocos2d-x打包Android
    cocos2d-x在win7下的android交叉编译环境
    Cocos2d-x之CCImage深入分析
    Eclipse开发C/C++之使用技巧小结
    TortoiseSVN安装使用
    cocos2d-x 2.2 study ------------------------ CCCallFunC家族
    cocos2d-x改底层之动态改变UIListView中的某项在链表中的位置
    汇编语言,以10进制的方式显示数字
    JVM
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/14648488.html
Copyright © 2020-2023  润新知