เพื่อ เข้ารหัส สตริงที่เราต้องการ encodeURIComponent() หรือ encodeURI() และเพื่อ ถอดรหัส สตริงที่เราต้องการ decodeURIComponent() หรือ decodeURI() . เริ่มแรกเราใช้ Escape() เพื่อ เข้ารหัส สตริง แต่เนื่องจากเลิกใช้แล้ว เราจึงใช้ encodeURI() .
ไวยากรณ์-1
encodeURIComponent(string);
ไวยากรณ์-2
decodeURIComponent(string);
ตัวอย่าง
ในตัวอย่างต่อไปนี้ เริ่มแรก จะใช้สตริงและ เข้ารหัส โดยใช้ encodeURI() และต่อมา ถอดรหัส โดยใช้ decodeURI() . ต่อมาทั้ง เข้ารหัส และ ถอดรหัส ผลลัพธ์ถูกแสดงในผลลัพธ์
<html>
<body>
<p id = "encoding"></p>
<script>
var str = "Tutorix is the best e-learning platform";
var enc = encodeURI(str);
var dec = decodeURI(enc);
var res = "After encoding: " + enc + "
</br>" + "After Decoding: " + dec;
document.getElementById("encoding").innerHTML = res;
</script>
</body>
</html> ผลลัพธ์
After encoding: Tutorix%20is%20the%20best%20e-learning%20platform After Decoding: Tutorix is the best e-learning platform