Escape quotes in JavaScript

Matt Dawdy picture Matt Dawdy · Jan 5, 2010 · Viewed 469.7k times · Source

I'm outputting values from a database (it isn't really open to public entry, but it is open to entry by a user at the company -- meaning, I'm not worried about XSS).

I'm trying to output a tag like this:

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

DESCRIPTION is actually a value from the database that is something like this:

Prelim Assess "Mini" Report

I've tried replacing " with \", but no matter what I try, Firefox keeps chopping off my JavaScript call after the space after the word Assess, and it is causing all sorts of issues.

I must bemissing the obvious answer, but for the life of me I can't figure it out.

Anyone care to point out my idiocy?

Here is the entire HTML page (it will be an ASP.NET page eventually, but in order to solve this I took out everything else but the problem code)

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

Answer

Aaron picture Aaron · Jan 5, 2010

You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.

Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, &quot;.