JavaScript encodeURI() encodeURIComponent()区别

对于无特殊参数的链接,都可以使用encodeURI()进行转码,那什么特殊情况需要用到encodeURIComponent()呢?通常是链接带着一些特殊参数的时候

1.1 encodeURI()

encodeURI()通常用于转码整个 URL,不会对URL 元字符以及语义字符进行转码,URL元字符:

URL 元字符:分号(;),逗号(,),斜杠(/),问号(?),冒号(:),at(@),&,等号(=),加号(+),美元符号($),井号(#)

语义字符:a-z,A-Z,0-9,连词号(-),下划线(_),点(.),感叹号(!),波浪线(~),星号(*),单引号('),圆括号(())

1.2 encodeURIComponent()

encodeURIComponent()通常只用于转码URL组成部分,如URL中?后的一串;会转码除了语义字符之外的所有字符,即元字符也会被转码

注:若整个链接被encodeURIComponent()转码,则该链接无法被浏览器访问,需要解码之后才可以正常访问。

Android

Uri.encode

IOS

// 导入Foundation模块
import Foundation

// 定义需要编码的URL字符串
let urlString = " development"

// 使用encodeURIComponent函数进行编码
if let encodedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
    print(encodedString)
}

Java URLEncoder 兼容 JavaScript encodeURIComponent

原本 JavaScript java
空格 %20 +
) ) %29
( ( %28
' ' %27
! ! %21
~ ~ %7E
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author linyufeng.
 * @date 2021/4/19 14:32
 **/
public class JsToolUtil {

    /**
     * 处理编码格式为js兼容模式
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeURIComponent(String str) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, "UTF-8")
                .replaceAll("\\\\+", "%20")
                .replaceAll("%28", "(")
                .replaceAll("%29", ")")
                .replaceAll("%27", "'")
                .replaceAll("%21", "!")
                .replaceAll("%7E", "~");
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "(A=\\"范广洲\\") AND (O='成都信息工程大学')";
        System.out.println(URLEncoder.encode(s, "UTF-8"));
        System.out.println(encodeURIComponent(s));
    }
}

ASCII Encoding Reference ASCII编码参考

Your browser will encode input, according to the character-set used in your page.您的浏览器将根据页面中使用的字符集对输入进行编码。