Escape quotes in JavaScript

533,927

Solution 1

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, ".

Solution 2

" would work in this particular case, as suggested before me, because of the HTML context.

However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
' becomes \x27
" becomes \x22

So your onclick would become:
DoEdit('Preliminary Assessment \x22Mini\x22');

This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert() is an easy test method for this).

I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.

Solution 3

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

Should do the trick.

Solution 4

Folks, there is already the unescape function in JavaScript which does the unescaping for \":

<script type="text/javascript">
    var str="this is \"good\"";
    document.write(unescape(str))
</script>

Solution 5

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

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

Related videos on Youtube

Matt Dawdy
Author by

Matt Dawdy

Programming is fun. And hard. But mostly fun. Well, actually, it changes hour by hour. #SOreadytohelp

Updated on February 29, 2020

Comments

  • Matt Dawdy
    Matt Dawdy about 4 years

    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>
    
    • Justin Johnson
      Justin Johnson over 14 years
      It's a good idea to make your onclick event attachment unobtrusive and to move all of your database information into a data island. Things will be cleaner and you'll actually get some sort of syntax error when your strings are escaped wrong.
    • Peter Mortensen
      Peter Mortensen about 9 years
    • Abhiram
      Abhiram about 5 years
      You can also use escape("string") and unescape("string") jquery methods
  • Matt Dawdy
    Matt Dawdy over 14 years
    Right, but wouldn't that be this? <a href="#" onclick="DoEdit('Preliminary Assessment \"Mini\"'); return false;">edit</a> I tried that, and it is still screwing up. This has got to be a simple WTF but for the life of me, I can't see it.
  • Matt Dawdy
    Matt Dawdy over 14 years
    Of course it does, because you aren't putting it directly in the attribute. To use your method, I'd have to create an array of JS strings, then do an arbitrary number of $("#divxxx")... assignments. Less than optimal, but thanks for the suggestion.
  • Matt Dawdy
    Matt Dawdy over 14 years
    Yikes. I was wondering why I naturally resorted to using ' for the attribute in the past. I just never delved into it all that deeply. Thanks.
  • kevin
    kevin over 13 years
    Is there any built-in JavaScript function that would escape the double quotes ? Apart from 'quo"'.replace('"', '&quot;') I can't find anything.
  • Aaron
    Aaron over 13 years
    It's not a javascript issue, it's an HTML/XML encoding issue: you can't have double-quote characters inside an attributes value w/o escaping them... otherwise browsers/parsers think you're ending the attribute value declaration.
  • Luis R.
    Luis R. over 12 years
    A combination of "escape"/"unescape" did what I needed. Thanks.
  • chug2k
    chug2k over 11 years
    escape/unescape are deprecated. although encodeURI does more than just quotes. gotochriswest.com/blog/2011/05/23/escape-unescape-deprecated
  • Joshua Burns
    Joshua Burns about 11 years
    example replacement code: 'mystring'.replace(/"/g, '&quot;');
  • scarver2
    scarver2 almost 11 years
    Thank you! Yours is the more correct answer because it is native JavaScript regardless of context.
  • Agustin Lopez
    Agustin Lopez over 10 years
    in the previous comment there is an extra quote. The code that works is 'mystring'.replace(/'/g, '&quot;');
  • Oliver
    Oliver about 10 years
    This is the correct answer, although in an HTML context using &quot; will, of course, work.
  • Adergaard
    Adergaard over 7 years
    I know this is an old question, but why not simply use encodeURIComponent() / decodeURIComponent() -- to my knowledge they do exactly what you want and have been around since Armstrong walked on the moon or thereabouts i.e. all browsers support it.
  • Bob Stein
    Bob Stein over 7 years
    @Adergaard, nope. Those are for a third escape scheme used by HTTP in URLs. encodeURIComponent('"') == '%22' (URI includes URL).
  • Adergaard
    Adergaard over 7 years
    @BobStein-VisiBone Well, in my usecase it works perfectly. I have data-attributes that need to contain user generated text and when using my suggestion it works like a charm from mandarine chinese to danish with all 14 excalmation points used.
  • Harun
    Harun almost 7 years
    I use org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(‌​text) to construct methodExpression in Java. Thanks.
  • Sean the Bean
    Sean the Bean over 6 years
    @AgustinLopez I don't see an extra quote in Joshua Burns' answer - just a double quote instead of a single quote.
  • thdoan
    thdoan about 6 years
    Note that &quot; is required in input values, i.e., <input value="\x22quoted string\x22"> will not work.
  • tsemer
    tsemer about 6 years
    @10basetom naturally, JavaScript escaping only works in a JavaScript context, like event handlers (onclick="..."). The value of a value attribute is not being processed within a JavaScript context, only within an HTML context.
  • chickens
    chickens about 6 years
    replacement code: 'mystring'.replace(/"/g, '\\x22').replace(/'/g, '\\x27')
  • leeCoder
    leeCoder about 3 years
    not working for me. it can't escape double quotes