Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách encode chuỗi trong JavaScript

JavaScript cung cấp escape() để encode chuỗi. Nhưng escape() đã deprecated, nên dùng encodeURI() hoặc encodeURIComponent().

Cú pháp

escape(string);
encodeURIComponent(str);

Ví dụ 1: escape() (cũ)

<html> <body> <script>    document.write(escape("Tutorix is the best e-learning platform!!!")); </script> </body> </html>

Kết quả

Tutorix%20is%20the%20best%20e-learning%20platform%21%21%21

Ví dụ 2: encodeURIComponent() (khuyến nghị)

<html> <body> <script>    document.write(encodeURIComponent("Tutorix is the best e-learning platform!!!")); </script> </body> </html>

Kết quả

Tutorix%20is%20the%20best%20e-learning%20platform!!!

Khác biệt: escape() không encode + @ * / _ - . và dùng Unicode 2-byte (%uXXXX) cho ký tự non-ASCII. encodeURIComponent() tuân thủ RFC 3986, dùng UTF-8 (%XX%XX).