How to use quotes within quotes properly - javascript

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.

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 do I use \ in a JavaScript string without escaping?

I have a string that is automatically generated by some code that encodes a Google Static Map polyline set of longitude,latitude. However, it places these pesky backslashes in the string which tries to escape the character after it.
enc:{eggEhwnQDYOCZuDv#q#H}#v#k#^v#TQh#Aw#j#AJJ#CZKA?LNZ[RUEALDDCRC#AJBBCJ\FAEACC?GM?K#GDGDEJC#BDADBFB#F#HANGH?DB#D\W|#g#QIZm#I#YoAO
I am not putting the encode directly into the HTML (where it would be fine) but instead using JavaScript to do it so this polyline encode gets put into a variable like so:
mapcoords:"path=color:0x00000000|fillcolor:0xFF9999|enc:{eggEhw`nQDYOCZuDv#q#H}#v#k#^v#TQh#`Aw#j#AJJ#CZKA?LNZ[RUEALDDCRC#AJBBCJ\FAEACC?GM?K#GDGDEJC#BDADBFB#F#HANGH?DB#D\W|#g#QIZm#I#YoAO"
Any suggestions how I go around the escaping? I've looked for the ampersand symbol for backslash but it seems one does not exist (if it would even help). So I am not sure how else to go about this.
You have to escape the backslash with a backslash like this:
var some_string = "my string with a backslash here: \\ ";
Most editors today have a find/replace function that you can use to replace a single backslash with two backslashes. If you use Notepad++ you can use CTRL+H to access this function, but as I said, most recent editors and IDE's have this function.
All you need to do is escape the escape character, so you simply get \\ instead of a single \. You will have to do this replacement wherever it is you're outputting that string to the client.

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

Difference between double and single quotes

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

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