How to use Built-in Functions In Javascript
JavaScript provides the encodeURIComponent()
function to encode special characters in a URI component, including HTML characters. To decode HTML entities back to their original characters, JavaScript offers the decodeURIComponent()
function.
Syntax:
const escapedString = encodeURIComponent(originalString);
const unescapedString = decodeURIComponent(escapedString);
Example: Implementation to showcase how to escape & unescape HTML characters using inbuilt functions.
// Original string containing HTML characters
const originalString =
'<script>alert("Geeksfor Geeks!")</script>';
// Escape HTML characters using encodeURIComponent
const escapedString =
encodeURIComponent(originalString);
console.log("Escaped String:", escapedString);
// Unescape HTML characters using decodeURIComponent
const unescapedString =
decodeURIComponent(escapedString);
console.log("Unescaped String:", unescapedString);
Output
Escaped String: %3Cscript%3Ealert(%22Geeksfor%20Geeks!%22)%3C%2Fscript%3E Unescaped String: <script>alert("Geeksfor Geeks!")</script>
How to escape & unescape HTML characters in string in JavaScript?
Escaping and unescaping HTML characters is important in JavaScript because it ensures proper rendering of content, preventing HTML injection attacks and preserving text formatting when displaying user-generated or dynamic content on web pages.