<button onClick="function("parameter")">Click</button>
<button onClick="function('parameter')">Click</button>
var variable = "value";
var variable = 'value';
Is there a difference?
No. They are interchangeable by design.
The only requirement is that you need matching pairs (either use " or ', but not both to signify a string).
See the spec for string literals:
StringLiteral:
" StringCharactersDQopt "
' StringCharactersSQopt '
When used within HTML, you need to be careful not to use the same delimiter in HTML attributes as the javascript ones (which is why your first example is not legal).
To function correctly you would need to change it to:
<button onClick='function("parameter")'>Click</button>
Yes, there's a difference when you mix it with HTML like you do: the first snippet will throw an exception because you need to escape the double quotes while the second will work (that's one of the reasons why you should avoid mixing markup with javascript). In pure javascript (a separate file) there's no difference.
The two are equivalent as long as the same one is used at both the beginning and end of the string literal. That said, choosing the correct one can avoid needless string escaping:
<button onClick="function("parameter")">Click</button> <!-- becomes -->
<button onClick="function('parameter')">Click</button>
var foo = "And the computer said: \"Hello, world!\""; // becomes
var foo = 'And the computer said: "Hello, world!"';
This has a clear advantage when using JavaScript to generate HTML, as is common in scripts using jQuery.
There is no difference. ' and " are interchangeable. Now you can't have a string like this: var my_var = 'hello world"; Opening and close quotes have to match. This does allow you to easily do: var my_variable = 'John says "I love JavaScript."' without having to escaping anything.
so this: <button onClick="function("parameter")">Click</button> won't work because you have opened and closed the onclick event prematurely "function("
It is the same. The only reason for having ' and " is, that you cannot nest them, for example, in given onClick example ->
onClick=" and there you need to use ' to encapsulate string "
The only time that there is a difference (that I am aware of) is in JSON: Double quotes are required around the keys and values.
And yes, everyone is right; Your first line should read like this or it will throw an error:
<button onClick='function("parameter")'>Click</button>
I prefer to use the double quotes only (if possible) because I'm used to C like languages (C, C++, C#) where string can be wrapped only with double quotes. (Single quotes is used, but to wrap char type)
To answer the question itself: same like all others said, no real difference - guess it exists to support cases when you mix JavaScript with HTML.
Related
I have this function :
function change_this(my_str)
{
$('#myDiv').html('<input value=\''+my_str+'\'>');
}
When I call this function with this :
onclick=change_this('Test '');
I see in the debugger that ' has been turned to a quote, and therefore the script does not work.
So my question is: how can I send a quote inside a string to a JS function?
I'm sure I'm not the first person to face this issue, I googled but did not find any simple explanations / answers.
You have two problems. This is because you have HTML embedded in JavaScript embedded in HTML which you are then generating HTML from by mashing together strings of JavaScript. You switch languages so many often it makes my head spin.
Problem 1: Getting the right string into the function
To include a single quote inside a string delimited by single quotes in JavaScript, you must escape them with a \.
onclick="change_this('Test \'');"
There is no need to use character references here. There are no ' with special meaning in the HTML. You would need to use ' three times if you had used ' instead of " to delimit the attribute value.
I'd avoid onclick entirely and favour data- attributes and JS event binding.
<input type="button" data-foo="Test '">
$("[type=button]").on('click', function (event) {
change_this( $(this).data('foo') );
});
Problem 2: Getting the right string into the HTML attribute value.
With the approach you are taking, you would need to convert the ' to '. Note that you would have to do it programatically because if you had it in the onclick attribute then it would be converted to ' by the HTML parser before the JavaScript engine even saw it.
Don't use your current approach though. Mashing strings together to make HTML is a nightmare.
Use DOM or something jQuery that vaguely resembles DOM.
var input = $("<input />").val(my_str);
$('#myDiv').empty().append(input);
I have a JS file with some XML in it, where the XML is supposed to get converted to a word by the server.
E.g.
var ip = "<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>";
This gets converted to:
var ip = "192.168.0.0";
However, in case the server doesn't work as intended, I don't want there to be a syntax error, and this is VERY important. Currently there would be a syntax error because the language uses both types of quotes. I can't think of a way to get around this, but perhaps there's another way to do quotes in JavaScript? Or to create a string?
For example, in Python I'd use triple quotes:
ip = """<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>"""
Anyone have a bright idea?
I have had to create strings without quotes for a project as well. We were delivering executable client javascript to the browser for an internal website. The receiving end strips double and single quotes when displayed. One way I have found to get around quotes is by declaring my string as a regular expression.
var x = String(/This contains no quotes/);
x = x.substring(1, x.length-1);
x;
Using String prototype:
String(/This contains no quotes/).substring(1).slice(0,-1)
Using String.fromCharCode
String.fromCharCode(72,69,76,76,79)
Generate Char Codes for this:
var s = "This contains no quotes";
var result = [];
for (i=0; i<s.length; i++)
{
result.push(s.charCodeAt(i));
}
result
In JavaScript, you can escape either type of quote with a \.
For example:
var str = "This is a string with \"embedded\" quotes.";
var str2 = 'This is a string with \'embedded\' quotes.';
In particular, your block of JavaScript code should be converted to:
var ip = "<lang:cond><lang:when test=\"$(VAR{'ip_addr'})\">$(VAR{'ip_addr'})</lang:when></lang:cond>";
In general, I always prefer to escape the quotes instead of having to constantly switch quote types, depending upon what type of quotes may be used within.
I was looking for a solution to the same problem. Someone suggested looking at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings which proved helpful. After reading about half the article, it stated that you can create strings with the backward tick character. (`)
Try this :)
document.getElementById('test').innerHTML = `'|'|'|"|"`
<div id="test" style="font-size:3em;"></div>
You can't create a string without using a single or double quote, as even calling the String() prototype object directly still requires you to pass it the string.
Inside XML you would use CDATA, but inside JS you'll have to just escape the '\"strings\"' "\'appropriately\'"
This is a combination of classic ASP and Javascript, we are trying to insert a single quote around each itemno but it is not working.
It is ending up looking like this: 10234,12343, instead of '10234','12343',
(The trailing comma I strip later)...
What can be done differently to keep the ItemNo's single quoted?
var Prefix_JS_Item = [<%For intA = 1 to intCount%><%="'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "',"%><%Next%>];
document.write(Prefix_JS_Item);
There have been two attempts so far but try this:-
var Prefix_JS_Item = [<%For intA = 1 to intCount%><%="""'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "'"","%><%Next%>];
document.write(Prefix_JS_Item);
Javascript supports both " and ' to enclose a string literal. So to include a ' in a literal you can use " to enclose the literal. Now in VB to include a " in string literal you double them to "".
BTW, don't "quote" me (sorry) but in javascript I think you can get away with the trailing comma.
The script is doing what you want. The way you verify is what is wrong.
After ASP executes you will have '10234','12343' inside the JavaScript. To see it go to "view source code" (CTRL + U) in your browser.
Then you write it to the document. To JavaScript '10234' the quotes are delimiters for a string. Therefore it will only write what is inside them.
If you still want to have quotes even when writing it to the document then:
... <%="""'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & """," %>
document.write(Prefix_JS_Item);
Which in javascript will look like: "'10234'","'12343'"
EDIT: To scape quotes in ASP you use another quote.
you have to escape the single quote
...<%="\'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "\',"%><%Next%>];
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When should I use double or single quotes in JavaScript?
Do "" and '' have different meanings in JavaScript?
Because I keep seeing those two usages in jQuery, for instance:
$("")
and
$('')
No, they mean the same thing; they are both just JavaScript string literals.
Having have multiple different quote styles is useful so that:
You can nest quotes without having to use escape sequences eg. "some string with 'single quotes' in it", or 'a string with "double quotes" in it', and
JavaScript strings can be conveniently used inside directly inside HTML, where double-quotes have a special meaning eg <button onclick="alert('foo')">Click me</div>
Read about strings in JavaScript. There is no difference.
But as HTML properties are often defined with double-quotes, I would use single-quotes, which makes code like
$('<a href="someurl" />')
easier to write.
Use the one with which you have less characters to escape inside the string.
Nope. It means the same.
They both are string delimiters. The only difference is if you can use " to enclose a string with ' in it, and you can use ' to enclose a string with " in it.
You can use either. I recommend sticking to one standard though throughout your project, things can sometimes get a little messy when interchanging between them when combining with server side code.
Outside of a string literal, No.
Inside of a string literal, Yes.
No... since isn't possible use "" inside "", the "" and '' make a good combination when need quote a string inside another.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is the difference between ‘ and “ in JavaScript?
Should i use ' or " char, to define a string in javascript?
Is it just a developer's choice?
I think, strings more offten contains ' char, so i prefer using of "(with inner " translated to \").
What do you think?
I prefer to use ", so after a full day of coding in JavaScript, I don't try to use ' on strings in C#
Most of the time I use html elements like that :
<input type="button" onclick="alert('test')" />
because of the attribute value has double quotes, I use single quote to represent javascript strings.
It's up to you. Double quotes are more common than single quotes in general, but I'll use single quotes if I have a double quote in my string. I don't force myself to only use double quotes.
var name = "John Doe";
alert('Hello there, "'+name+'", if that is your real name.');
I normally use the single quote simply because in ASPX it doesn't conflict with double quotes inside serverside scripts (<%= %>). Other than that it is a developer's choice.
I also prefer ", but tend to switch to ' if I have strings that contain HTML or XML code. But it's more a matter of taste since, if I remember correctly, ' is allowed in HTML and XML for attributes as well, so you could also do it the other way round.
My personal preference for Python (where, like JS, single and double quotes are equivalent) is for single quotes, just because that way there are "fewer pixels showing" (OK, a somewhat arbitrary criterion;-). But, it IS a matter for a "style guide" (either a personal one or one shared by a group of programmers working on the same codebase) rather than any objective rule.
There are two choices in Javascript solely for the developer to choose whichever is convenient at the time. There is no semantic or syntactic difference, unlike in other languages. So, use both to wild abandon!