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.
Related
Going through the Vue online guide, I ran into something that looks like a quote escaping problem. More specifically, I am toying around with the example provided in chapter components->events.
The template in my component looks like
"<div class=\"blog-post\">\
<h3>{{ post.title }}</h3>\
<button #click=\"$emit(\\\"enlarge-text\\\")\" >Enlarge text</button>\
<div v-text=\"post.content\"></div>\
</div>"
And instead of the expected button, I get the string
")" >Enlarge text
I managed to circumvent my issue by replacing the two occurrences of the double escape \\\" by single quotes, but I have the feeling there is something I am missing here. Can you help me to understand what is happening here or provide me pointers towards the relevant doc?
Any explanation is welcome.
As I'm sure you're aware, escaping is used to include characters literally within text that would otherwise be interpreted as having a special meaning. Establishing which characters have special meaning requires us to look at the 'channels' that will be interpreting that text and then select a suitable escaping mechanism for those channels.
In this case the text will be interpreted by 3 channels...
As a JavaScript string literal.
By the Vue template compiler, which has a format very similar to HTML.
Expressions within the template, such as binding expressions, will be treated as JavaScript, potentially including yet more JavaScript string literals.
JavaScript string literals use the \ character to introduce escape sequences. However, the HTML-like syntax used for Vue templates do not. As for HTML they use entities prefixed with &.
So, working backwards, we first need to consider how we escape the expressions within the template. In this case that is $emit("enlarge-text"). As the string "enlarge-text" doesn't contain any special characters we don't need to apply any escaping. Easy so far.
Then we need to escape the template 'HTML'. Now we do run into problems because the #click attribute is delimited with double-quotes and its value contains double-quotes. Obviously we could dodge the issue by using different types of quotes but if we instead hit the problem head-on we'd need to use & entities to escape those quotes. i.e. " for ". That gives us:
<button #click="$emit("enlarge-text")">Enlarge text</button>
I believe this is where the escaping in the question goes wrong as it attempts to use \ escaping to escape the attribute value.
If we were using SFCs then that would be sufficient. But for a template written as a string literal we've still got one more level of escaping to apply, using \. The original quotes around enlarge-text are no longer present so they don't require any further escaping but we still have the quotes around the attribute. That gives us:
"<button #click=\"$emit("enlarge-text")\">Enlarge text</button>"
However, all that said, the usual conventions when specifying string templates are:
Use backticks for the template string itself, giving better multi-line support.
Use double-quotes around attributes.
Use single-quotes for strings within expressions.
Obviously there are cases where that isn't possible, such as if you want to use backticks within an expression, but if you stick to those conventions as much as possible you usually won't need to escape anything. When you do it'll also be a lot simpler to perform the escaping as you aren't using the same delimiters at all three levels.
You could use template literal / template string for this:
let tpl = `<div class="blog-post">
<h3>{{ post.title }}</h3>
<button #click="$emit('enlarge-text')">Enlarge text</button>
<div v-text="post.content"></div>
</div>`;
Not only does it read better, it is way more maintanable than multiple escaped quotes.
You can wrap enlarge-text with single quotes. Like this:
<button #click=\"$emit('enlarge-text')\">Enlarge text</button>
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]\"";
I am trying to find a way to check if a string contains a specific sequence of characters in JScript.
In my case, I am trying to see if the string is "DPObject" followed by a number. Such as "DPObject3" or "DPObject14".
Thank you!
if (/DPObject\d+/.test(string)) {....}
Javascript String has an indexOf method you can use to check if a String contains a particular substring .
If you need to test for patterns , like "DPObject" followed by an integer , probably you need to use Regexes . ( http://www.regular-expressions.info )
It's javascript , or js for short - not JScript .
Then you should use a regular expression. I think this would be something like :
var re = new RegExp("^DPObject([0-9]+)$");
re.test(someString);
This ensures there is at least only one digit after DPObject.
The "^" at the beginning is to ensure the string starts with DPObject. Check references on regexps for this kind of problems :)
edit: added "$" to mark the end of the string, the updated should be more "solid"
There are a couple of ways:
Use Javascripts indexOf method
Use Javascript Regular Expressions
Use JQuery's contains function
Regular expressions are the most powerful and elegant way of doing it. They syntax makes sense after a while (honestly). ;-)
Good luck.
<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.
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!