Escaping HTML characters in a string means replacing the:
<
>
"
'
&
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
replace
method will return a new string by replacing the matched pattern with the replacement string.
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);