Sometimes, we want to use PHP HtmlSpecialChars equivalent in JavaScript.
In this article, we’ll look at how to use PHP HtmlSpecialChars equivalent in JavaScript.
How to use PHP HtmlSpecialChars equivalent in JavaScript?
To use PHP HtmlSpecialChars equivalent in JavaScript, we use the string replace
method.
For instance, we write
const escapeHtml = (text) => {
const map = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
return text.replace(/[&<>"']/g, (m) => {
return map[m];
});
};
to replace the HTML special characters in the text
string with the ones listed in the map
object.
We use the g
flag to replace all matches of the regex.
Conclusion
To use PHP HtmlSpecialChars equivalent in JavaScript, we use the string replace
method.