JavaScript: should i use ' or " char to define string? [duplicate] - javascript

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!

Related

ENT_QUOTES in a JS string

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);

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

Escape HTML using jQuery [duplicate]

This question already has answers here:
Escaping HTML strings with jQuery
(27 answers)
Closed 9 years ago.
I came up with a hack to escape HTML using jQuery and I'm wondering if anyone sees a problem with it.
$('<i></i>').text(TEXT_TO_ESCAPE).html();
The <i> tag is just a dummy as jQuery needs a container to set the text of.
Is there perhaps an easier way to do this? Note that I need the text stored in a variable, not for display (otherwise I could just call elem.text(TEXT_TO_ESCAPE);).
Thanks!
That's a pretty standard way of doing it, my version used a <div> though:
return $('<div/>').text(t).html();
This isn't technically 100% safe though as Mike Samuel notes but it is probably pretty safe in practice.
The current Prototype.js does this:
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
But it used to use the "put text in a div and extract the HTML" trick.
There's also _.escape in Underscore, that does it like this:
// List of HTML entities for escaping.
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
// Regex containing the keys listed immediately above.
var htmlEscaper = /[&<>"'\/]/g;
// Escape a string for HTML interpolation.
_.escape = function(string) {
return ('' + string).replace(htmlEscaper, function(match) {
return htmlEscapes[match];
});
};
That's pretty much the same approach as Prototype's. Most of the JavaScript I do lately has Underscore available so I tend to use _.escape these days.
There is no guarantee that html() will be completely escaped so the result might not be safe after concatenation.
html() is based on innerHTML, and a browser could, without violating lots of expectations, implement innerHTML so that $("<i></i>").text("1 <").html() is "1 <", and that $("<i></i>").text("b>").html() is "b>".
Then if you concatenate those two individually safe results, you get "1 <b>" which will obviously not be the HTML version of the concatenation of the two plaintext pieces.
So, this method is not safe by deduction from first principles, and there's no widely followed spec of innerHTML (though HTML5 does address it).
The best way to check if it does what you want is to test corner cases like this.
That should work. That's basically how the Prototype.js library does it, or at least how it used to do it. I generally do it with three calls to ".replace()" but that's mostly just a habit.

What is the difference between ' and " in JavaScript?

<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.

Do "" and '' have different meanings in JavaScript? [duplicate]

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.

Categories