How to encode a string in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

<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. 

Live Demo

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

Output

Tutorix%20is%20the%20best%20e-learning%20platform!!!
raja
Updated on 03-Jul-2020 07:43:05

Advertisements