ฟังก์ชัน encodeURIComponent() ใช้เข้ารหัส (encode) ส่วนประกอบของ URI (component) โดยแทนที่ ทุกอักขระ ยกเว้นอักขระ alphanumeric และ - _ . ! ~ * ' ( ) ด้วยรูปแบบ %xx
ไวยากรณ์
encodeURIComponent(uriComponent)
ตัวอย่าง
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var result1 = encodeURIComponent('https://www.qries.com/'); document.write(result1); document.write("<br>"); var result2 = encodeURIComponent('https://www.tutorialspoint.com/'); document.write(encodeURIComponent(result2)); </script> </body> </html>
ผลลัพธ์
http%3A%2F%2Fwww.qries.com%2F http%253A%252F%252Fwww.tutorialspoint.com%252F
ข้อสังเกตจากตัวอย่างที่ 2:
การเข้ารหัสซ้ำ (double encoding) จะทำให้ % กลายเป็น %25 → ควรหลีกเลี่ยง
อักขระที่ไม่ถูกเข้ารหัส:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
กรณีใช้งานจริง:
- เข้ารหัส query parameter values
- เข้ารหัส path segments
- สร้าง URL อย่างปลอดภัยจาก user input
- POST data (application/x-www-form-urlencoded)