Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
CodeCrack Avatar asked Jan 17 '12 22:01

CodeCrack


People also ask

Which is the invalid escape sequence in JavaScript?

A string contains a literal character that is a reserved character in the Regex class (for example, the '(' or open parentheses character). Placing a '\' (backslash) in front of the character in the regular expression generates an 'Invalid escape sequence' compilation error.

How do you escape a string in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

Do I need to escape in JavaScript string?

The only characters you normally need to worry about in a javascript string are double-quote (if you're quoting the string with a double-quote), single-quote (if you're quoting the string with a single-quote), backslash, carriage-return (\r), or linefeed (\n).

What is the correct escape notation for a new line in a string JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

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') 
});
like image 163
Adam Rackis Avatar answered Sep 28 '22 03:09

Adam Rackis


You can avoid that mess by creating elements like this:

var content = $( "<a>", {
    href: "#",
    text: "whatever",
    click: $.proxy( displayContent, 0, "TEST" )
});
like image 39
Esailija Avatar answered Sep 28 '22 05:09

Esailija