How to Escape HTML Special Characters in JavaScript?
Dec 10, 2024 am 10:12 AMEscaping 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;"); }
For instance, if you have the following unsafe text:
<p>I want to display text with special characters like &," and </p>
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>');
The resulting escapedText will be:
<p>I want to display text with special characters like &amp;,"\ and</p>
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;'); };
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
