[javascript] Escaping double quotes in JavaScript onClick event handler

The simple code block below can be served up in a static HTML page but results in a JavaScript error. How should you escape the embedded double quote in the onClick handler (i.e. "xyz)? Note that the HTML is generated dynamically by pulling data from a database, the data of which is snippets of other HTML code that could have either single or double quotes. It seems that adding a single backslash ahead of the double quote character doesn't do the trick.

<script type="text/javascript">
    function parse(a, b, c) {
        alert(c);
    }
</script>

<a href="#x" onclick="parse('#', false, '<a href=\"xyz'); return false">Test</a>

This question is related to javascript html escaping dom-events

The answer is


You may also want to try two backslashes (\\") to escape the escape character.


It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;


I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to escaping

Uses for the '&quot;' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class