How do I escape quotes in JavaScript?

I’m working with a database value that includes quotes, and I need to output it within a JavaScript function call inside an HTML attribute. For example, I have a value like this:

Prelim Assess "Mini" Report

And I want to output a tag like this:

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

However, I keep running into issues where Firefox is cutting off the JavaScript function call after the space in “Assess” even though I’ve tried escaping the quotes with \". How can I properly escape quotes in JavaScript to prevent this problem from happening?

Having worked with front-end JavaScript for over a decade, escaping quotes is something that comes up way more often than you’d expect. The most straightforward way for javascript escape quotes is by using a backslash (). It’s simple and reliable."

Example:

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

Here, the \" ensures the double quotes inside the JavaScript string are treated as part of the content, not as string delimiters. Whenever you deal with javascript escape quotes inside attributes or function calls, this method keeps your code safe and working.

The code provided is demonstrating the use of single quotes for JavaScript string delimiters to avoid the need for escaping double quotes inside the string. This approach is helpful when the string contains double quotes, as it simplifies the syntax and improves readability.

For example, consider the following anchor tag:

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

In this example, the entire JavaScript string is enclosed within single quotes ('). This allows the use of double quotes (") inside the string—such as those surrounding "Preliminary Assessment \"Mini\""—without causing a conflict with the outer delimiters. However, since there are nested quotes around the word Mini, those still need to be escaped to ensure the string is interpreted correctly by the browser.

This technique is particularly useful in avoiding syntax errors or the need for excessive escaping when dealing with complex strings that include quotes.