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(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#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 &,"\ 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;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#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!