乐趣区

关于urlencode:Javascript-URL-encoding

URL 编码,有时也称为百分比编码,是一种将 URL 中的任何数据编码为能够在 internet 上传输的平安格局的机制。URL 编码还用于为提交具备 application/x-www-form-urlencoded MIME 类型的 HTML 表单筹备数据。

encodeURIComponent()

留神,不应该应用 encodeURIComponent() 函数对整个 URL 进行编码。它应该只用于对查问字符串或门路段进行编码:

var baseUrl = 'https://www.google.com/search?q='
var query = 'Hellö Wörld@Javascript'

// encode only the query string
var completeUrl = baseUrl + encodeURIComponent(query)
console.log(completeUrl)

// https://www.google.com/search?q=Hell%C3%B6%20W%C3%B6rld%40Javascript

encodeURI()

语法:encodeURI(URI)

参数 URI:A complete URI.

const uri = 'https://mozilla.org/?x=шеллы';
const encoded = encodeURI(uri);
console.log(encoded);
// expected output: "https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"

encodeURI vs encodeURIComponent

const set1 = ";,/?:@&=+$#"; // Reserved Characters
const set2 = "-_.!~*'()";   // Unreserved Marks
const set3 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$#
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)

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)

URLEncoder (在线)

退出移动版