Computer >> Computer tutorials >  >> Programming >> Javascript

How to encode a string in JavaScript?


Javascript has provided escape() function to encode a string. But since the escape() function is now deprecated, it is better to use encodeURI() or encodeURIComponent()

syntax-1

escape(string);

syntax-2

encodeURIComponent(str);

Example-1

In the following example, using the escape() method the string "Tutorix is the best e-learning platform!!!" is encoded and displayed the result in as shown in the output.

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

Output

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


Example-2

In the following example, using the encodeURIComponent() method the provide string is encoded and displayed the result as shown in the output. 

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

Output

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