decodeURI()
Giải mã URL đầy đủ. Không giải mã các ký tự dành riêng: ; , / ? : @ & = + $ #.
decodeURI("https://example.com/path%20name?query=value");
// "https://example.com/path name?query=value"
decodeURIComponent()
Giải mã thành phần (component) của URL. Giải mã tất cả ký tự được mã hóa bao gồm cả ký tự dành riêng.
decodeURIComponent("path%20name%3Fquery%3Dvalue");
// "path name?query=value"
So sánh trực quan
| Input | decodeURI | decodeURIComponent |
|---|---|---|
| %3A (:) | %3A | : |
| %2F (/) | %2F | / |
| %3F (?) | %3F | ? |
| %23 (#) | %23 | # |
| %20 (space) | (space) | (space) |
Khi nào dùng cái nào?
- decodeURI(): Chuỗi URL hoàn chỉnh từ
location.href,encodeURI(). - decodeURIComponent(): Giá trị tham số từ query string, dữ liệu từ
encodeURIComponent().
Ví dụ thực tế
// URL đầy đủ
var fullUrl = "https://site.com/search?q=javascript%20tutorial&page=1";
var decodedFull = decodeURI(fullUrl); // giữ ? & =
// Chỉ lấy giá trị tham số q
var qValue = "javascript%20tutorial";
var decodedParam = decodeURIComponent(qValue); // "javascript tutorial"