Javascript equivalent to Ruby's single quotes? [duplicate] - javascript

This question already has answers here:
Does JavaScript have literal strings?
(6 answers)
Closed 7 years ago.
In Ruby, if you use single quotes to make a string, the program parses it so that the output is literally what you wrote.
For example, if you create a string the following way:
variable_a = 'my\nname\nis\nOliver\nQueen'
the output of puts variable_a is
>>my\nname\nis\nOliver\nQueen
However, if you instead use double quotes when building the string, like so:
variable_b = "my\nname\nis\nOliver\nQueen"
the output of puts variable_b would be
>>my
>>name
>>is
>>Oliver
>>Queen
I am looking for a way in Javascript that does just what the single quotes do in Ruby, so that there will be less mistakes when trying to properly build a string that contains backslashes, and other characters that would 'break' the intended string.

Single and double quotes in Javascript are equivalent. The only real reason to use one over the other is preference, and avoiding escaping embedded quotes, e.g.
"Don't need to escape this apostrophe."
or
'No need to escape this "quoted" word.'
Unless you are talking about JSON. In JSON you must use double quotes or it is considered a syntax error by many parsers.

Related

JavaScript: What is the difference between ', ", and `? [duplicate]

This question already has answers here:
Are double and single quotes interchangeable in JavaScript?
(23 answers)
Closed 3 years ago.
I've been learning JavaScript for not too long, and somethings that I notice a lot, but doesn't make sense to me are the different operators (if I can call them that) that defines a string. What I mean by that is the single quote ('), the double quote (") and the apostrophe-thing(`). I have come to realize that ``` is used when you want to use the variable or something (eg
console.log(`this is my string ${ str }`)
or something like that. I don't know too much about these and I would like to know what their different purposes are (or in the very least, what they are called)
Thanks!
P.S. I realize that this question topic causes some problems with the markdown. I have no idea how to fix it.
The apostrophe thing ` is general used for multi line strings while single and double quotes are used for single line strings. Single quotes are used to enclose double quotes.
For example: say I have a string like so: "I ate a fruit". If I want to print that string with the quotation marks I would use console.print(' "I ate a fruit" ').

Javascript eval fails on complicated json array [duplicate]

This question already has answers here:
JSON Javascript escape
(4 answers)
Closed 7 years ago.
I want to convert a json string to object by eval, but it fails with error like:
Uncaught SyntaxError: Unexpected identifier VM250:1
below is my string:
'[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
Seems there is something wrong in the bold part, but i don't know how to fix it
The code below is not working
var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);
The code below is working so i think the data structure of this json string is ok
var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);
Also tried with $.parseJSON with no luck
It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:
[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
// ^ ^
I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.
In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:
'[{"option_in_json":"[{\\"option\\": ... }]"}]'
Better of course if you are not putting it in a string literal in the first place.
var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
// ^-- don't wrap in "" so no need to escape inner double quotes.
console.dir(JSON.parse(m));

Is there a reason to use the single quote instead of the double quote in Javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Double or Single Quotes in JavaScript
In Javascript, you can either use double quotes or single quotes around strings, and it means exactly the same thing:
var a = 'hello';
var b = "hello";
alert(a === b); //alerts true
I was reading some of Douglas Crockford's code, and it looks like he usually uses single quotes around string literals.
Further, most of the high rep people who answer Javascript questions around here seem to use single quotes around strings (example).
Since I usually use double quotes around strings (mostly just out of habit), I'm starting to feel self-conscious about all the answers I've given here that use double quotes. I haven't heard of any particular reason why one should use one over the other, since, as far as I can tell, they are interchangeable.
Is there a reason why all of the Javascript ninjas use single quotes? Should I use single quotes too? Will there be some unexpected fatal consequences if I continue using double quotes?
Strings ideally are enclosed in double quotes. There are cases where you want to use single quotes when you're wrapping text that has double quotes within them like:
var txt = 'This "should" be escaped';
Without single quotes, you'd need to escape the double quotes which makes them bit ugly (matter of taste though).
If you're in ASP.Net world, usually to workaround the nastiness of DataBinder expression, you wrap strings in single quotes.
Plus I find single quotes easier to type.
Another place where you must use double quotes is constructing JSON objects:
var obj = { "a": 1 }; // valid
var obj = { 'a': 1 }; // invalid
Either way, being consistent is most important. Choose one style and stick to it throughout the code (except when you run into escaping issues).
You can choose either one, the main thing is to be consistant.
They can be used interchangably however most languges such as c# " needs to be escaped however ' does not so its slightly simpler to use '
I believe that is is a primarily stylistic choice, however when it comes to quote or string escaping it can affect your string.
Overall, ensure that you are consistent whichever method you chose.

javascript string difference [duplicate]

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

single quotes versus double quotes in js [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to Use Double or Single Quotes in JavaScript
Are there any differences between single and double quotes in javascript?
No, is the right answer most of the time. However if you want to write valid JSON, then you should use double quotes for object literals.
No, except in double quotes you can put single quotes.
e.g. "Don't not do this"
And in single quotes you can put double quotes.
e.g. 'John said "Do this"'
No difference. Just make sure you close the string with whatever you open it with.
Much more sensible to me than other languages (looking at you, C# and PHP...) where single quoted strings are either character literals, or don't expand escaped characters.
One is slightly wider, so you may have a few extra characters disappear to the right (as opposed to the slimmer version) in your favourite IDE.
Seriously though, I always use ', because if I need to quote a HTML element attribute, I always use " and I can't be bothered escaping like so
var html = "hello"
You would mostly use " unless in a position in where you can't escape it. ( It is neater to most developers, Don't ask why )
Also "$myVar" in php will allow the string to have the variables value. ( I know its not javascript, but another example..
In bash,
echo "What is your name?\nMy name is $(whoami)."
will run the function / command whoami.
<button onclick="dosomething(\"test\")">Test</button> Won't work
<button onclick="dosomething("test")">Test</button> Won't work
<section id='"Where-As">
<button onclick="dosomething('test')">Test</button>
<!-- will work -->
</section>
P.S: Valid JSON objects should be using double quotes.
Other fun with different quotes:
console.log('\n\n\n\n'); // Will give you \n\n\n\n as a string.
console.log("\n\n\n\n"); // Will give lines.

Categories

Resources