Để encode chuỗi: encodeURIComponent() hoặc encodeURI(). Để decode: decodeURIComponent() hoặc decodeURI(). Trước dùng escape() nhưng đã deprecated, giờ dùng encodeURI().
Cú pháp
encodeURIComponent(string);
decodeURIComponent(string);
Ví dụ
Chuỗi được encode bằng encodeURI() rồi decode bằng decodeURI(). Cả hai kết quả hiển thị.
<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>
Kết quả
After encoding: Tutorix%20is%20the%20best%20e-learning%20platform After Decoding: Tutorix is the best e-learning platform
Phân biệt:
encodeURI(): Không encode ký tự đặc biệt URL (: / ? # [ ] @), dùng cho URL đầy đủencodeURIComponent(): Encode tất cả ký tự đặc biệt, dùng cho tham số query string- Tương ứng:
decodeURI()/decodeURIComponent()