Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน decodeURIComponent() ใน JavaScript

ฟังก์ชัน decodeURIComponent() ใช้ถอดรหัส (decode) URI component ที่เข้ารหัสแล้ว กลับเป็นสตริงต้นฉบับ

ไวยากรณ์

decodeURIComponent(encodedURI)

ตัวอย่าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var encodedData = encodeURIComponent('https://www.qries.com/?x=шеллы');       document.write("เข้ารหัส: "+encodedData);       document.write("<br>");       var decodedData = decodeURIComponent(encodedData);       document.write("ถอดรหัส: "+decodedData);    </script> </body> </html>

ผลลัพธ์

เข้ารหัส: http%3A%2F%2Fwww.qries.com%2F%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B ถอดรหัส: https://www.qries.com/?x=шеллы

ความแตกต่างระหว่าง decodeURI และ decodeURIComponent:

ฟังก์ชันถอดรหัสไม่ถอดรหัส (reserved chars)
decodeURIURI ทั้งหมด; , / ? : @ & = + $ #
decodeURIComponentURI component (ส่วน)ไม่มี (ถอดรหัสทุกตัว)

ข้อผิดพลาดที่พบบ่อย:

  • URIError: พยายามถอดรหัสสตริงที่เข้ารหัสไม่ถูกต้อง (เช่น %GG)
  • ต้องใช้คู่กับ encodeURIComponent() เท่านั้น