zoukankan      html  css  js  c++  java
  • URL Encode

    URL只能使用指定的字符:英文字母、阿拉伯数字和部分特定字符。

    其它字符会被编码转义成可用的格式。

    URI = scheme:[//authority]path[?query][#fragment]


    JS中有相应的编码/解码函数:encodeURI(uri)/decodeURI(uri),encodeURIComponent(uri)/decodeURIComponent(uri)

    encodeURI(uri) , encodeURIComponent(uri)

    将一个字符串编码成URI

    decodeURI(uri), decodeURIComponent(uri)

    将一个字符串解码成URI


    encodeURI(uri)/decodeURI(uri) 针对整个URI,不会编码/解码那些对于URI字符串有特殊含义的保留字符(reserved characters),不会编码/解码那些组成一个完整URI所需的那些保留字符。

    encodeURIComponent(uri)/decodeURIComponent(uri)针对URI的组成部分,保留字符(reserved characters)同样会被编码/解码

    var set1 = ";,/?:@&=+$#";  // Reserved Characters
    var set2 = "-_.!~*'()";   // Unreserved Marks
    var set3 = "ABC abc 123"; // Alphanumeric Characters + Space
    var set4 = "https://www.baidu.com/s?wd=a b c"
    
    console.log(encodeURI(set1)); // ;,/?:@&=+$#
    console.log(encodeURI(set2)); // -_.!~*'()
    console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
    console.log(encodeURI(set4)); // https://www.baidu.com/s?wd=a%20b%20c
    
    console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
    console.log(encodeURIComponent(set2)); // -_.!~*'()
    console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
    console.log(encodeURIComponent(set3)); // https%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3Da%20b%20c

    另:

    URL中不能包含空格(space),空格通常会被编码成 `%20` 或者 `+` 。不推荐将空格编码成 `+` 。

    1. `%20` 更通用,也是最新的标准。对于scheme:[//authority]path[?query][#fragment],所有的空格都可以被编码成 `%20` ,而只有[?query][#fragment]中的空格允许被编码成 `+`。

    2. 对于decodeURI(uri)/decodeURIComponent(uri),默认并不会将`+`解码成空格。

    对于已经使用`+`编码过的URL字符串,可以使用以下方式来解码,从而正确替换掉编码成`+`的空格。

    encodeURIComponent(s).replace(/+/g, '%20')


    Reserved Characters

    !*'();:@&=+$,/?#[

    ]

    Unreserved Characters
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    abcdefghijklmnopqrstuvwxyz
    0123456789-_.~

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

  • 相关阅读:
    JavaSE—集合框架
    JavaSE——集合框架
    RocketMq 在Netty 下是如何进行消息封装传输
    SpringBoot 初始化流程以及各种常见第三方配置的源码实现
    Java 重要知识点,踩过的坑
    Mysql 知识储备以及InnoDB
    java 编程英语单词,语句
    PlantUML
    Rocketmq broker 消息仓库
    AutowiredAnnotationBeanPostProcessor 的一些思考
  • 原文地址:https://www.cnblogs.com/cnsec/p/13547595.html
Copyright © 2011-2022 走看看