This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between single quotes and double quotes in Javascript
Sorry guys, but here I am asking a stupid question.
In Javascript, do we use " or ' ?
Looking at the code below, it seems that " and ' behave differently?
var html = '<dt> <img src="' + imageurl + '" /> </dt>';
Can somebody explain to me the different between " and ' ?
In javascript there is no difference. Both are valid for enclosing a string i.e. defining a string literal.
Your example shows double quotation marks that are a value inside a string. They are clearly part of markup that is held in that string. Their presence is unrelated to the javascript language, and that string could equivalently have been defined:
var html = "<dt> <img src=\"" + imageurl + "\" /> </dt>";
Usually the only reason one is chosen over the other is convenience. For example, when quoting markup (as in your example) there are often many double quotes (although single quotes are just as valid), so it's easier to define the string with single quotes, and not have to escape slash every quote that should be part of the string (as oppose to defining the string's boundaries).
On the other hand, free text often contains many apostrophes, in which case it's often easier to enclose the string with double quotes: "It'll be easier this way, that'll save me some work".
It depends on what you open and close with.
A ' will end on the next detected ' and a " will end on the next detected "
Your example could also be written:
var html = "<dt> <img src='" + imageurl + "' /> </dt>";
There is no difference, it just depends on what you open with
You can use single or double quotes to enclose an expression. As long as the same type of quote closes the expression, all is good.
If you plan on including HTML in the string, you should use single quotes... that way you don't have to escape the double quotes.
If you used double quotes in the above, you would need to escape the inside quotes, eg.
var html = "<dt> <img src=\"" + imageurl + "\" /> </dt>";
In javascript, they are the same. You can switch between them for easier escaping of potential quotes in the string literal itself.
Be careful, because in some other languages (like perl) there is a difference: in that case, double quoted string would allow variable interpolation, while single quoted strings would not. Javascript at present does not support this feature.
You can use either form of quote. These are identical:
var html1 = "<bold>Hi</bold>";
var html2 = '<bold>Hi</bold>';
Whichever delimiter you choose to start the string with, the next unescaped occurrence of that delimiter signals the end of the string.
Where life gets interesting is when there are embedded quote marks in your string itself. For example, supposed you want to assign this to a javascript variable:
<img src="http://www.google.com/images/logo1w.png">
In that case, you a couple choices. You could use this which escapes the embedded double quotes:
var html1 = "<img src=\"http://www.google.com/images/logo1w.png\">";
or you can use this:
var html2 = '<img src="http://www.google.com/images/logo1w.png">';
I find that the latter looks a lot cleaner.
Related
I need to escape single quotes in JavaScript function parameters to avoid this:
onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);"
But I need to escape them inside a function call since I do not know the values that will be passed (db variables I can't escape from the database).
Is there a function that allows me to do something like the following?
onclick="Javascript:function(escape(param1), escape(param2), escape(param3));"
JSON.stringify(plainTextStr).replace(/&/, "&").replace(/"/g, """)
will produce a string you can safely embed in a quoted attribute and which will have the same meaning when seen by the JavaScript interpreter.
The only caveat is that some Unicode newlines (U+2028 and U+2029) need to be escaped before being embedded in JavaScript string literals, but JSON only requires that \r and \n be escaped.
Escape the apostrophe with a backslash:
onclick="INSERT_PRODUCT('188267','WILL AND GRACE ','32311','L\'ANNIVERSARIO DI NOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);"
It's maybe not totally clear from the question, but assuming that all you want is to send this to a PHP script for storing in a database, you of course would ideally utilize PHP's various methods such as stripslashes() -- but if you're really not trying to get too fancy, simply adding 1 slash in front of any single quote is enough to send a SQL query right into PHP from the client-side. It's not safe, but maybe not necessary either.
str.replace(/'/g, "\\'"); // escaping \ with \, so used 2x
does the trick., like for example in something like this:
var body = $('#body').val().replace(/'/g, "\\'");
myCustomSQLqueryFunction("UPDATE mytable SET `content`='"+ body +"';" );
MySQL will now store your body like you see it in the form field.
This function worked for me (it removes and restores the quote again):
Guessing that the data to be sent is the value of an input element,
var Url = encodeURIComponent($('#userInput').val().replace("'","\\'"));
Then get the original text again:
var originalText = decodeURIComponent(Url);
var cmpdetail = cmpdetail.replace(/'/g, "\\'");
its working for me.
I prefer to use single quote for defining JavaScript strings. Then I escape my embedded double quotes as follows.
This is how I do it, basically str.replace(/[\""]/g, '\\"').
var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');
//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>
I encountered a similar issue recently, and solved it by replacing the single quote with the corresponding unicode (')
Initially my code was this, resulting in me getting results that were cut off (e.g. Jane's Coffee became just Jane in the output).
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
When I introduced unicode replacement (shown below), I got the exact output I wanted
b.innerHTML += "<input type='hidden' value='" + arr[i].replace("'", "'") + "'>";
I'm struggling with a complex nested quotes statement here :
var name = "foo";
$("#list").append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=PRINT_VAR_NAME_HERE;' data-transition='slide'>PRINT_VAR_NAME_HERE</a></li>");
I am able to print the variable's value fine in the second position by using : "+name+"
But not sure how to get it done in the first position.
(I have used 'PRINT_VAR_NAME_HERE' as a placeholder for the first and second positions)
Any ideas ? Thanks.
Just use the string-delimiters (the ") to break the string and concatenate the string with your variable, and escape (with the backslash) any quotes that you need to appear in the string itself:
$("#list")
.append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=\"" + name + "\"' data-transition='slide'>"+ name + "</a></li>");
I am, of course, assuming that you want to quote the variable in the string, otherwise I couldn't see what the problem would be.
I was running into the same issue of trying to figure out how to nest quotes in a javaScript in order to generate HTML. I was hitting a particular snag in the 'onclick' area because I was including a variable within it. In addition, the browser was interpreting my quotes incorrectly.
The solution: You have to explicitly tell the browser which quotes you ARE using and where. And you do this by using ' for single-quote, and " for double-quotes.
Hopefully this is helpful to someone...
document.getElementById("item-controls-" + id).innerHTML = "<span class=\'controls\' id=\'save-control\' onclick='saveForm(\"" + id + "\")'>save</span> ...
I realized I've been switching between them with no understanding as to why, and am finding it hard to search for.
' ' and " " are the same thing; they are used to define string literals.
Things without quotes can be an identifier, keyword, non-string literal, property name or a number (may have missed one).
Examples:
"hello world" literal (string)
'hello world' literal (string) with same contents
document identifier (object)
{ a: 1 } property name
if keyword (start conditional statement)
3.4 literal (number)
/abc/ literal (regex object)
String literals that are enclosed in single quotes don't need escaped double quotes and visa versa, e.g.:
'click me' HTML containing double quotes
"It's going to rain" String containing single quote
' ' and " " used to quote string literal and represents string(s) whereas literal without quote are variables (name of variable, constant) know as identifier, example
variable = 'Hello'; (Here `variable` is identifier and 'Hello' is string literal)
var = "Ho There"
You might question, what is the difference between ' (single quote) and " (Double quote)
Difference is ,strings within " if have special character then they need to escape. Example:
Variable = "hi " there"; ---> here you need to escape the " inside string like
Variable = "hi \" there";
But if using, ' then no need of escaping (unless there is a extra ' in string). You can hve like
var = 'Hello " World"';
" and ' are interchangeable (but need to be used together).
myObject["property"] and myObject.property are also interchangeable. $var foo = "property"; myObject[foo] as well (per comment below).
A quick jsfiddle around and both single and double quotes escape control codes etc.
In latter days I have had errors from HTML where double quotes have not been used, and if you look at the spec for JSON you'll note it is a double quote that is asked for when quoting string literals. So it is double quotes that is the convention I think, for historical reasons.
However! In these days of writing server side JS I must admit I tend to be pulled back to my C roots and double quote where I want escaped chars and single quote strings that are effectively literal chars and never likely to contain escaped chars (even though this is essentially non-productive behaviour). Besides which most of my JS is coffeescript nowadays anyway, nobody ever wrote javascript for elegance, CS is a different kettle of fish though.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
single quotes versus double quotes in js
When to Use Double or Single Quotes in JavaScript
What is the difference (if any) between the javascript strings defined below?
var str1 = "Somestring";
var str2 = 'Somestring';
"" and '' mean two very different things to me predominantly writing code in C++ :-)
EDIT: If there is no difference why are there two ways of achieving the same thing and which is considered better practice to use and why. Thanks!
Javascript treats single and double quotes as string delimiters.
If you use single quotes, you can use double quotes inside the string without escaping them.
If you use double quotes, you can use single quotes inside the string without escaping them.
Both examples evaluate to the same thing.
alert(str1 == str2); // true
alert(str1 === str2); // true
Why two ways? Due to the way javascript allows you to mix the two, you can write html attributes out without messy escapes:
var htmlString1 = "<a href='#'>link</a>";
var htmlString2 = 'link';
As for best practice, there is no convention. Use what feels best.
Personally, I like making sure the Javascript I emit matches the HTML (if I double quote attributes, I will delimit JS string with a ', so emitted attributes will use ").
In Javascript a string is a sequence of zero or more Unicode characters enclosed within single or double quotes (' or "). Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes.
In client-side JavaScript programming, JavaScript code often contains strings of HTML code, and HTML code often contains strings of JavaScript code. Like JavaScript, HTML uses either single or double quotes to delimit its strings. Thus, when combining JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the other style for HTML.
No difference at all.
I believe the answer is there is no difference. They are both strings.
Here would be the usage of '
var mynewhtml = '<body class="myclass" ></body>';
or using "
var mynewhtml = "<body class='myclass' ></body>";
this also works but IMO is harder to read
var mynewhtml = "<body class=\"myclass\" ></body>";
document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
The above code is my javascript. Problem is printing hello or any other string. If I just type 123 in place of hello, it does give alert. But am not able to use a string like hello there. Normally a string in an alert function is kept inside quotes ' ' but the entire content is inside double quotes and I have already used single quote at the beginning of onclick function. I tried using Escape character ("\") but it didnt help. Any suggestions?
Try this:
document.getElementById("img").innerHTML = '<img src="/sitepath/' + imgg + '.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
If you use apostrophes as delimiter for the HTML attributes, you have to HTML encode the apostrophes that you put inside the attribute:
document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
I prefer using apostrophes as string delimited in Javascript and quotation marks as delimiters for HTML attributes. Then you just escape the apostrophes that you have inside the Javascript string:
document.getElementById("img").innerHTML='< img src="/sitepath/'+imgg+'.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
To put any string inside a Javascript, inside an HTML attribute, inside a string in Javascript, you do:
escape any string delimiters in the string
HTML encode the Javascript code
escape any string delimiters in the HTML string
You have JavaScript inside HTML inside JavaScript. That's naturally confusing. Better to avoid the string-slinging problems of quoting and escaping (which, got wrong, can easily lead to security holes when user-submitted data is used), and do it the DOM way:
var img= new Image();
img.src= '/sitepath/'+imgg+'.jpg';
img.width= 72;
img.height= 44;
img.onclick= function() {
alert('hello');
};
document.getElementById('img').appendChild(img);
I tried using Escape character ("\") but it didnt help
Javascript is different from C#, you just use it twice at a time, example: alert('We are\\'t going to go')
It doesn't matter if your outer quotes are single or double. You can escape a character within an outer string with a backslash... \' becomes ' within the string itself. Either Darin's or Masood's example will work. But Masood is ignorant in reference to a need to use double-quotes as the outside enclosure.
what if someone needs to send a variable instead of a string "hello"? Something like this:
function showContent(toPopulate) {
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(*toPopulate*);'>show</a>"
}
function showOtherContent(toPopulate) {...}
so how to send toPopulate as a variable to showOtherContent()?
The above is solved like this:
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(\"" + toPopulate + "\");'>show</a>"
You will need to use the double quotes and escape it in the onclick attribute
document.getElementById("img").innerHTML="<img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick=\"alert('hello');\" />";