Home >Web Front-end >JS Tutorial >How do I escape quotes in JavaScript for displaying data in HTML?

How do I escape quotes in JavaScript for displaying data in HTML?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 07:36:03606browse

How do I escape quotes in JavaScript for displaying data in HTML?

Escaping Quotes in JavaScript: Programmatic Data Output in JavaScript

When displaying data from a database in HTML, managing special characters like quotes can be crucial to prevent browser parsing issues. As you rightly observed, attempting to escape quotes in JavaScript with the backslash character () is insufficient within an HTML context.

To address this, the correct approach is to replace the double quotes with the XML entity representation, ". This entity will prevent browser confusion and ensure the JavaScript call is correctly interpreted.

For example, your provided HTML code:

<a href="#" onclick="DoEdit('Preliminary Assessment \"Mini\"'); return false;">edit</a>

Can be modified to effectively escape the quotes:

<a href="#" onclick="DoEdit('Preliminary Assessment &amp;quot;Mini&amp;quot;'); return false;">edit</a>

By using the XML entity representation, you can now safely output the required data without encountering any parsing errors. Remember, this technique is particularly important when dealing with data that may contain user-entered content, even if it is restricted within the company's network.

The above is the detailed content of How do I escape quotes in JavaScript for displaying data in HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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