CodeCrack
CodeCrack

Reputation: 5373

Am I escaping the strings incorrectly in JavaScript?

I am trying to create a clickable link in javascript

var content = '<a href=\"#\" onclick=\"displayContent(\"TEST\")\">Whatever</a>';

$("#placeHolder").html(content);

but I keep getting an error

Uncaught SyntaxError: Unexpected token }

Is that not the correct way to escape double quotes and create a link?

Upvotes: 6

Views: 943

Answers (4)

H Bellamy
H Bellamy

Reputation: 22725

You don't need to escape them at all!

var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'; 

$("#placeHolder").html(content); 

Just have it like that, as you don't need to escape " usually, when in embeded in a ';

But you do need to escape ' characters when it is a parameter in a function.

Upvotes: 0

Nathan Taylor
Nathan Taylor

Reputation: 24606

You only need to escape quotes when they are the same type as used by your opening and closing quotes. In your example, you are unnecessarily escaping double quotes because your string is wrapped in single quotes. That being said, because of the double quotes in onclick statement the parser will have issues with the the call to displayContent().

Try this, instead:

var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'; 

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83376

You only need to escape the single quotes

var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'

As bozdoz says:

You escape single quotes that are within single quotes; you escape double quotes that are within double quotes


But why not do

var content = $("<a />").attr("href", "#").text("Whatever").click(function(){
     displayContent('TEST')
});

Or as Nathan says:

var content = $('<a href="#">Whatever</a>').click(
     function() { displayContent('TEST') 
});

Upvotes: 7

Esailija
Esailija

Reputation: 140234

You can avoid that mess by creating elements like this:

var content = $( "<a>", {
    href: "#",
    text: "whatever",
    click: $.proxy( displayContent, 0, "TEST" )
});

Upvotes: 2

Related Questions