Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quotes in JavaScript

People also ask

How do you escape quotes in JavaScript?

To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!

What is escape () in JS?

Definition and Usage The escape() function was deprecated in JavaScript version 1.5. Use encodeURI() or encodeURIComponent() instead. The escape() function encodes a string. This function makes a string portable, so it can be transmitted across any network to any computer that supports ASCII characters.

How do you put an escape character in a quote?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.


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


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


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

Should do the trick.


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>