How to use PHP HtmlSpecialChars equivalent in JavaScript?

Spread the love

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 = {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#039;",
  };

  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.

Leave a Reply

Your email address will not be published. Required fields are marked *