Difference between double and single quotes - javascript

I have an MVC app where I'm inserting some text into the DOM using jQuery.
If I use:
$("#toggle").text('<%: translated.Show %>');
The text is rendered.
If I use:
$("#toggle").text("<%: translated.Show %>");
Where resource string is wrapping in double quotes it throws a JavaScript error, note the single quotes wrapping the working version and double quotes wrapping the erroneous version.
Can anyone explain why, I thought there was little difference between single and double quotes in Javascript.
The 'translated.Show' string does not contain quotes just plain text.

The only difference between double and single quotes in JS is that inside single quotes, single quotes must be escaped while inside double quotes, double quotes must be escaped.
The problem is most likely that the data inside translated.Show contains a double quote (despite your assurances that it does not… quote characters are considered part of plain text).
Make sure your are following Rule 3: JavaScript Escape Before Inserting Untrusted Data into JavaScript Data

Related

Javascript is adding a slash between Parenthesis and Quote

Why is Javascript adding a slash between the parenthesis and quote, when I'm trying to copy it. I want it removed when doing paste ctrl-v.
Console Javascript F12 in Chrome
var testData = 'By.XPath("//test")'
var resultArray = [];
resultArray.push(testData)
console.log(resultArray);
copy(resultArray);
Ctrl-V in Paste New Data, It has a slash between parenthesis and "
"By.XPath(\"//test\")"
You have a string that contains double quotes, inside an array:
[ 'By.XPath("//test")' ]
Since you're using single quotes around double quotes, there is no issue. But if you used double quotes (which are functionally equivalent in JavaScript to single quotes), like this: "By.XPath("//test")", you would get a syntax error, because JavaScript would think you had two strings, "By.XPath" and ")", with some garbage in-between (//test). Removing special significance of a character is called "escaping", and is done in JavaScript using the backslash (not slash) character (\). Thus, to put a double quote inside a double-quoted string, you need to write "By.XPath(\"//test\")", where \" tells JavaScript that this " is not end of the string, but just a simple quote character.
Now, if you used copy(testData), you would get the exact string inside your clipboard: By.XPath("//test"). However, you copied an array that contains this string; this stringifies the array. When an array is turned into a string, you get brackets around comma-separated list of elements, and if an element is a string, it is double-quoted. So while you got around the need of escaping by using single quotes, JavaScript refuses to choose and always uses double quotes, and then has to use the double quotes to make sure the result is not garbage ("By.XPath("//test")").

How to use quotes within quotes properly

If you create an HTML element with JS using a string like the following, how can you add the extra quotes required within an onclick event? Since I have already exhausted double and single quotes, is there an elegant way of making this work?
var foo_td="<td onclick='window.open('newpage.html', '_blank')'>Open Page</td>";
You need to replace innermost single quotes ' with double quotes " and escape them with single backslash \, like this:
var foo_td="<td onclick='window.open(\"newpage.html\", \"_blank\")'>Open Page</td>";
Demo
Why escape quotes at first place
This is because when the onclick event will be fired on this td and if there are no quotes (if quotes not escaped), then it will look for a variable named newpage.html and _blank and give an error because these variables (most likely) won't exist.
Why not only single backslash with single quote
Single-backslash will only escape the string for the evaluation of this string expresion, and by the time this value is stored in a string it will ignore this backslash.
Why not double backslash with single quote
By the time nodes are rendered on DOM (can check this on Developer Tools of your browser), its attribute values are enclosed inside a double quote rather than a single quote. So, it will be rendered as this and hence give an error.
<div onclick="window.open(\" newpage.html\',="" \'_blank\')'="">Open Page</div>
So, based on three reasons given above you should always escape double quote if you want to pass a string parameter to a function call from an attribute.

Javascript regex ends with pattern

I'm trying to write a regex in javascript to identify string representations of arbitrary javascript functions found in json, ie. something like
{
"key": "function() { return 'I am a function'; }"
}
It's easy enough to identify the start, but I can't figure out how to identify the ending double quotes since the function might also contain escaped double quotes. My best try so far is
/"\s*function\(.*\)[^"]*/g
which works nicely if there are no double quotes in the function string. The end of a json key value will end with a double quote and a subsequent comma or closing bracket. Is there some way to retrieve all characters (including newline?) until a negated pattern such as
not "/s*, and not "/s*}
... or do I need to take a completely different approach without regex?
Here's is the current test data I'm working with:
http://regexr.com/39pvi
Seems like you want something like this,
"\s*function\(.*\)(?:\\.|[^\\"])*
It matches also the inbetween \" escaped double quotes.
DEMO

Double quotes vs single quotes in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to Use Double or Single Quotes in JavaScript
Are there differences between ' and "
I am wondering if there is a difference between using single quotes vs double quotes in JavaScript (JQuery selectors etc.).
Both seem to work just fine, so is there a difference?
The difference is that you don't need to escape single quotes in double quotes, or double quotes in single quotes. That is the only difference, if you do not count the fact that you must hold the Shift key to type ".
It doesn't matter unless you're trying to write JSON, in which case you must use double quotes for object literals.
There is no special difference between single and double quotes (like it is in PHP).
The only actual difference is that you can write a double quote " in a single-quoted string without escaping it, and vice versa.
So, if you are going to output some HTML in your JavaScript, like this:
<div id = "my_div"></div>
single quotes are more useful :-)
They work the same, but they must match. You cannot start a string with a single and end with a double, or the opposite. Other than that, they are interchangeable.

How can I accommodate a string with both single and double quotes inside of it in JavaScript

I have an application, and it is fed some HTML. It then needs to put that HTML into a string. This HTML contains single and double quotes. Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?
I guess if it is not possible, does anyone know a simple and easy way to escape these quotes so I can put it in a string? Keep in mind, part of this string will be JavaScript that I will later need to execute.
You need to escape the quotation characters with \:
var someString = 'escape all the quotation marks \"\'';
Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?
No. JavaScript string literals are delimited with either single quotes or double quotes. Those are the only choices.
does anyone know a simple and easy way to escape these quotes so I can put it in a string?
Do you mean in a string literal?
var str = "var foo=\"bar\"; function say(it) { alert('It is: ' + it); say(foo);";
Or programmatically?
str = str.replace(/"/g, '\\"');
An easy way to escape the quotes is to use the javascript escape function.
http://www.w3schools.com/jsref/jsref_escape.asp
Use the escape function to replace special characters (including single and double quotes). You can then use the unescape function to return the string to it's normal state later if necessary.
For example:
var data = 'hello my name is "James"';
alert(escape(data)); //Outputs: hello%20my%20name%20is%20%22James%22

Categories

Resources