ใช้ decodeURI() สำหรับถอดรหัส URL ทั้งหมด และ decodeURIComponent() สำหรับส่วนประกอบ
ตัวอย่างจากบทความ
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Check</button>
<p id="demo"></p>
<script>
function display() {
var uri = "welcome msg.jsp?name=\u00e5mit&sub=programming";
// first encode
var encode = encodeURI(uri);
var decode = decodeURI(encode);
var result = "Encode= " + encode + "<br>" + "Decode= " + decode;
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
decodeURI() vs decodeURIComponent()
| ฟังก์ชัน | ใช้กับ | ถอดรหัส |
decodeURI() | URL ทั้งหมด | %XX sequences ยกเว้น reserved chars (; , / ? : @ & = + $ #) |
decodeURIComponent() | ส่วนประกอบ (query value) | %XX sequences ทั้งหมด |
ตัวอย่างการใช้งาน
1. ถอดรหัส URL เต็ม
var fullUrl = "https://example.com/path%20with%20spaces?query=value";
decodeURI(fullUrl);
// "https://example.com/path with spaces?query=value"
2. ถอดรหัส Query Parameter
var encodedParam = "hello%20world%26special%3Dchars";
decodeURIComponent(encodedParam);
// "hello world&special=chars"
// decodeURI จะไม่ถอด & และ =
decodeURI(encodedParam);
// "hello world&special=chars" (เหมือนกันเพราะไม่มี reserved char ที่เข้ารหัส)
3. กรณี Error: Malformed URI
try {
decodeURI("%E0%B8"); // incomplete UTF-8 sequence
} catch (e) {
console.error("Invalid URI sequence"); // URIError
}
// ใช้ try-catch เสมอ
function safeDecode(uri) {
try {
return decodeURI(uri);
} catch (e) {
return uri; // คืนค่าเดิมถ้า decode ไม่ได้
}
}
การใช้งานร่วมกับ URLSearchParams (Modern)
const url = new URL('https://example.com/search?q=hello%20world&lang=th');
// ดึงค่า query parameter (decode อัตโนมัติ)
console.log(url.searchParams.get('q')); // "hello world"
console.log(url.searchParams.get('lang')); // "th"
// วนลูปทั้งหมด
for (const [key, value] of url.searchParams) {
console.log(key, value); // แล้ว decode แล้ว
}
Encoding/Decoding Pair
| Encode | Decode | ใช้สำหรับ |
| encodeURI() | decodeURI() | Full URL |
| encodeURIComponent() | decodeURIComponent() | Query params, path segments |
| escape() (deprecated) | unescape() (deprecated) | Legacy only |
Best Practice
- ใช้
URL และ URLSearchParams API แทนการจัดการสตริงด้วยมือ
- Always wrap decode ใน try-catch
- ไม่ใช้
escape()/unescape() (deprecated)