What does ' ', and " ", and no quotes mean in Javascript? - javascript

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.

Related

Javascript \x escaping

I've seen a few other programs that have something like this:
var string = '\x32\x20\x60\x78\x6e\x7a\x9c\x89';
And I had to try to fiddle with the numbers and letters, to find the text I wanted to display.
I'm wondering if there is a function to find the \x escape of a string, like string.toUpperCase() in JS. I'm using processingJS, but it will be okay for me to use other programming languages to find the ASCII for \x.
If you have a string that you want escaped, you can use String.prototype.charCodeAt()
If you have the code with escapes, you can just evaluate them to get the original string. If it's a string with literal escapes, you can use String.fromCharCode()
If you have '\x32\x20\x60\x78\x6e\x7a\x9c\x89' and want "2 `xnz" then
'\x32\x20\x60\x78\x6e\x7a\x9c\x89' == "2 `xnz"
If you have '\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89' which is a literal string with the value \x32\x20\x60\x78\x6e\x7a\x9c\x89 then you can parse it by passing the decimal value of each pair of hex digits to String.prototype.fromCharCode()
'\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89'.replace(/\\x([0-9a-f]{2})/ig, function(_, pair) {
return String.fromCharCode(parseInt(pair, 16));
})
Alternatively, eval is an option if you can be sure of the safety of the input and performance isn't important1.
eval('"\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89"')
Note the " nested in the ' surrounding the input string.
If you know it's a program, and it's from a trusted source, you can eval the string directly, which won't give you the ASCII, but will execute the program itself.
eval('\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89')
Note that the input you provided is not a program and the eval call fails.
If you have "2 `xnz" and want '\x32\x20\x60\x78\x6e\x7a\x9c\x89' then
"2 `xnz".split('').map(function(e) {
return '\\x' + e.charCodeAt(0).toString(16);
}).join('')

Is the following javascript safe from arbitrary code execution?

I'm contributing to a javascript framework which has the equivalent of the following code:
eval("'" + user_input.replace(/'/g, "'") + "'");
I know this is terrible -- no need to persuade me. What I want to know is, can I inject arbitrary code here?
At first glance the user_input.replace("'", "'") would seem to prevent me from breaking out of the string. However I can pass in newlines e.g. \nalert(123)\n, but then the result is always a syntax error, e.g.
'
alert(123)
'
Is there actually a vector for code injection here, other than just causing a syntax error?
While this is undoubtedly a worrisome pattern, it's safe if used exactly in the way described. The only character that can terminate a single-quoted string in Javascript is the single quote character. So long as that character does not appear in the string interpolated into the single quotes, it cannot possibly be interpreted as anything other than a string.
About the worst thing I can think of that you could do is end a string with a backslash, which would result in an unterminated string, e.g. if user_input were:
example\
then the evaluated code would be
'example\'
which would result in a syntax error, because the string contained in the eval is never terminated. However, if the real eval is actually more complex, this is exploitable. For example, if the code were:
var escaped_input = user_input.replace(/'/g, "&39;");
eval("'" + escaped_input + "' some more stuff '" + escaped_input + "'");
then it could be exploited with an input like:
; alert(1); // \
which would result in:
'; alert(1); // \' some more stuff '; alert(1); // \'
^^^^^^^^^
in which the underlined content would be evaluated, because the quote that was supposed to exit the string was escaped, turning the next single quote into a closing quote! To be safe, I'd recommend escaping or replacing backslashes if possible (unless you're explicitly trying to use eval() to deal with them, in which case you might just catch the exception).

Any other way to terminate a string in javascript other than double quotes when begun with double quotes?

E.G.
<script>
a="MY INPUT";
</script>
So I am filtering the double quotes ' " ' to ensure that input cannot breakout. An alternative would be to apply an escape '\"'. Is there another string terminator in javascript that could terminate a string begun with double quotes that I am unaware of? I know that the nullbyte doesn't apply.
Thanks
You can use single quotes as well:
var a = 'my string';
Use single quotes.
<script>
a='MY INPUT';
</script>
This one also will work
$("#purchase").html('<option value="1">Classics</option>');
According to the specification, there are or only two ways to define string literals:
StringLiteral ::
" DoubleStringCharactersopt "
' SingleStringCharactersopt '
So, it seems that double quoted strings can only be terminated by double quotes.

In Javascript do we use " or ' ? Are they different? [duplicate]

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.

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

Categories

Resources