Home > Web Front-end > JS Tutorial > How to Escape HTML Special Characters in JavaScript?

How to Escape HTML Special Characters in JavaScript?

Barbara Streisand
Release: 2024-12-10 10:12:14
Original
624 people have browsed it

How to Escape HTML Special Characters in JavaScript?

Escaping HTML Special Characters in JavaScript:

As you endeavor to display text on an HTML page via a JavaScript function, you may encounter the challenge of escaping HTML special characters. These characters, such as < (less than) and > (greater than), can cause unexpected rendering issues.

Fortunately, JavaScript provides an efficient way to handle this task:

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&amp;/g, "&amp;amp;")
        .replace(/</g, "&amp;lt;")
        .replace(/>/g, "&amp;gt;")
        .replace(/&quot;/g, "&amp;quot;")
        .replace(/'/g, "&amp;#039;");
}
Copy after login

For instance, if you have the following unsafe text:

<p>I want to display text with special characters like &," and
</p>
Copy after login

You can use the escapeHtml function to escape the special characters:

const escapedText = escapeHtml('<p>I want to display text with special characters like &," and</p>');
Copy after login

The resulting escapedText will be:

<p>I want to display text with special characters like &amp;,"\ and</p>
Copy after login

This escaped text can now be safely displayed on the HTML page without any rendering issues.

For modern web browsers, you can simplify the escaping process using the replaceAll function:

const escapeHtml = (unsafe) => {
    return unsafe.replaceAll('&amp;', '&amp;amp;').replaceAll('<', '&amp;lt;').replaceAll('>', '&amp;gt;').replaceAll('&quot;', '&amp;quot;').replaceAll("'", '&amp;#039;');
};
Copy after login

By implementing one of these solutions, you can effectively escape HTML special characters in JavaScript, ensuring the seamless display of text on your web pages.

The above is the detailed content of How to Escape HTML Special Characters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template