decodeURIComponent()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Hàm decodeURIComponent() giải mã một thành phần Uniform Resource Identifier (URI) đã được tạo trước đó bởi encodeURIComponent() hoặc một hàm tương tự.

Try it

function containsEncodedComponents(x) {
  // ie ?,=,&,/ etc
  return decodeURI(x) !== decodeURIComponent(x);
}

console.log(containsEncodedComponents("%3Fx%3Dtest")); // ?x=test
// Expected output: true

console.log(containsEncodedComponents("%D1%88%D0%B5%D0%BB%D0%BB%D1%8B")); // шеллы
// Expected output: false

Cú pháp

js
decodeURIComponent(encodedURI)

Tham số

encodedURI

Một thành phần đã được mã hóa của Uniform Resource Identifier.

Giá trị trả về

Một chuỗi mới biểu thị phiên bản đã giải mã của thành phần Uniform Resource Identifier (URI) đã được mã hóa.

Ngoại lệ

URIError

Được ném ra nếu encodedURI chứa ký tự % không được theo sau bởi hai chữ số thập lục phân, hoặc nếu chuỗi thoát không mã hóa một ký tự UTF-8 hợp lệ.

Mô tả

decodeURIComponent() là thuộc tính hàm của đối tượng toàn cục.

decodeURIComponent() sử dụng cùng thuật toán giải mã như được mô tả trong decodeURI(). Nó giải mã tất cả các chuỗi thoát, bao gồm cả những chuỗi không được tạo bởi encodeURIComponent, như -.!~*'().

Ví dụ

Giải mã thành phần URL tiếng Cyrillic

js
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"

Bắt lỗi

js
try {
  const a = decodeURIComponent("%E0%A4%A");
} catch (e) {
  console.error(e);
}

// URIError: malformed URI sequence

Giải mã tham số truy vấn từ URL

decodeURIComponent() không thể được dùng trực tiếp để phân tích tham số truy vấn từ URL. Nó cần một chút chuẩn bị.

js
function decodeQueryParam(p) {
  return decodeURIComponent(p.replace(/\+/g, " "));
}

decodeQueryParam("search+query%20%28correct%29");
// 'search query (correct)'

Đặc tả kỹ thuật

Specification
ECMAScript® 2027 Language Specification
# sec-decodeuricomponent-encodeduricomponent

Tương thích trình duyệt

Xem thêm