Home > Web Front-end > JS Tutorial > How to Escape Quotes in JavaScript for HTML Attributes?

How to Escape Quotes in JavaScript for HTML Attributes?

Barbara Streisand
Release: 2024-11-13 12:34:02
Original
1061 people have browsed it

How to Escape Quotes in JavaScript for HTML Attributes?

Escaping Quotes in JavaScript for HTML Attributes

When outputting values from a database to an HTML page, it's crucial to handle certain characters, such as quotes, correctly to prevent unexpected behavior.

Consider the example where a string retrieved from a database needs to be used as a parameter in an onclick HTML attribute:

<a href="" onclick="DoEdit('DESCRIPTION');">Click Me</a>
Copy after login

If DESCRIPTION contains a space and quote, such as:

Prelim Assess "Mini" Report
Copy after login

Firefox prematurely truncates the onclick attribute after the space in "Assess" due to the double quote after "Assess".

To resolve this issue, it's necessary to "escape" the troublesome quotes. While using the JavaScript escape character is insufficient in this HTML context, a different approach is required.

The solution involves replacing the double quote character with its corresponding XML entity representation, ". This will ensure that the double quote is interpreted as a string delimiter within the HTML attribute:

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

By escaping the double quotes in the string, the onclick attribute now operates as intended.

The above is the detailed content of How to Escape Quotes in JavaScript for HTML Attributes?. 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