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

วิถถอดรหัส String หลังจากเข้ารหัสใน JavaScript

เพื่อ เข้ารหัส (Encode) String ต้องใช้ encodeURIComponent() หรือ encodeURI() และเพื่อ ถอดรหัส (Decode) ใช้ decodeURIComponent() หรือ decodeURI() เดิมใช้ escape() เข้ารหัส แต่ Deprecated แล้ว จึงใช้ encodeURI() แทน

Syntax-1

encodeURIComponent(string);

Syntax-2

decodeURIComponent(string);

ตัวอย่าง

ในตัวอย่างนี้ รับ String แล้ว เข้ารหัส ด้วย encodeURI() แล้ว ถอดรหัส ด้วย decodeURI() แสดงทั้ง เข้ารหัส และ ถอดรหัส ใน Output

<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