How to escape & unescape HTML characters in string in JavaScript
Escape HTML
Escaping HTML characters in a string means replacing the:
- less than symbol (<) with
< - greater than symbol (>) with
> - double quotes (") with
" - single quote (’) with
' - ampersand (&) with
&
Let’s suppose we have an HTML element as a string:
<script> alert("hi") </script>
We can escape the HTML of the string using the replace method of the string.
function escape(htmlStr) {return htmlStr.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");}console.log(escape("<script>alert('hi')</script>"));
In the code above, we have used regex to globally replace the:
<with<>with>"with"'with'&with&
The
replacemethod will return a new string by replacing the matched pattern with the replacement string.
Unescape HTML
Unescaping HTML in a string does the reverse of what we have done above, by replacing:
<with<>with>"with"'with'&with&
function unEscape(htmlStr) {htmlStr = htmlStr.replace(/</g , "<");htmlStr = htmlStr.replace(/>/g , ">");htmlStr = htmlStr.replace(/"/g , "\"");htmlStr = htmlStr.replace(/'/g , "\'");htmlStr = htmlStr.replace(/&/g , "&");return htmlStr;}let unEscapedStr =unEscape(`<script>alert('hi')</script>`);console.log(unEscapedStr);