jquery escaping quotes not quite right - javascript

I have attempted escaping quotes out from this jquery bit of code and I'm not quite getting it. As well as the correct answer could I get the format for escaping quotes in jquery? Specifically I'm only trying to put the rdata.result[i].name variable into a string to pass it over. Thanks!
filling += "<a onclick=\"inserttictac("+rdata.result[i].uid+","+rdata.script[0]+",\'"+rdata.result[i].name+"\',"+rdata.result[i].front+","+rdata.result[i].back+","+rdata.result[i].side+")\'>Select</a>";

You don't need to escape the single quotes, only the double quotes.
You are using double quotes for string definition, so only escape those.
filling += "<a onclick=\"inserttictac("+rdata.result[i].uid+","+rdata.script[0]+",'"+rdata.result[i].name+"',"+rdata.result[i].front+","+rdata.result[i].back+","+rdata.result[i].side+")\">Select</a>";

Related

js_string with double quoted expression

We have a FTL that has -
<a href='javascript:func("${event.title}");'>Link</a>
When the value has an apostrophe, like Norman'S Birthday - it breaks.
We used js_string to fix it -
Link
But we also had to change the double quotes around $expression to single quotes - this does Not work with double quotes.
Question -
Is there a way to fix this with the original double quotes around the $expression ?
Something like -
<a href='javascript:func("${event.title?js_string}");'>Link</a>
Note the above does not work.
You need two kind of escaping applied here: JavaScript string escaping and HTML escaping. You need both, as the two formats are independent, and the JavaScript is embedded into HTML.
How to do that... the primitive way is event.title?js_string?html, but it's easy to forget to add that ?html, so don't do that. Instead, use auto-escaping (see https://freemarker.apache.org/docs/dgui_quickstart_template.html#dgui_quickstart_template_autoescaping). If you can't use that form of auto-escaping for some reason (like you are using some old FreeMarker version and aren't allowed to upgrade), put the whole template into <#escape x as x?html>...</#escape>. In both cases, you can just write ${event.title?js_string}, and it will just work.
However, if you are using #escape, ensure that the incompatible_improvements setting (see https://freemarker.apache.org/docs/pgui_config_incompatible_improvements.html) is at least 2.3.20, or else ?html doesn't escape '.
Modify the value of event.title so that single quotes are replaces with &apos; and double quotes are replaces with ", then you won't have to worry at all about which kind of quotes you use for the rest of it.
?js_string should be outside curly brackets {}. Now you should use double quotes " " around href value, if you wanna handle single quotes ' ' inside the string and vice versa. Single and double quote can not be used in same string, so either of them needs to be replaced to other.
solution:
Link
Same expression can be used in JavaScript to handle special characters

escape special characters in javascript (jquery) function

I have this line that appending this in jquery:
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\'ple','awayteam')");
Notice the "exam\'ple"... i escaped the ' with \'
so when clicking the button, the function active should work.
this is the function active:
function active(hometeam,awayteam){
alert("if this is alerted, it works!");
}
when i click the button it should alert "if this is alerted, it works!", but it's not alerting it. and it think because when i use the function, this is the outpot:
function active(exam\'ple,awayteam){
when i appending the same thing with a word that does not contain " ' ", it is working.
You need to escape the backslash in your parameters for the active function, instead of the apostrophe.
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\\'ple','awayteam')");
To escape a string to append it to that code with php, you can use regular expressions. The following will work in your case.
// Replaces a backslash with four backslashes: The 'append' function will interpret it as two backslashes; the 'active' function, as only one.
$str = preg_replace("/\\\\/", "\\\\\\\\\\\\\\\\", $str);
// Replaces an apostrophe with two backslashes and an apostrophe, then javascript will append only one backslash and an apostrophe, escaping that way an apostrophe.
$str = preg_replace("/'/", "\\\\\\\\'", $str);
// Replaces quotations with a backslash and quotations: the quotations will be escaped inside the append function, so one quotations will be printed out on your HTML
$str = preg_replace("/\"/", "\\\\\"", $str);
If you don't know what a regular expression (regex) is, I suggest you researching a bit about how to use them. They will help you a lot.
EDIT: By some reason, the last program needed double of backslashes to work. Updated.
You don't need to escape single quotes when the string is double-quoted. It's best practice to wrap the whole string in single quotes, allowing you to use double quotes without the need to escape. (or single quotes with it all wrapped up in doubles).
For example:
$("#thing").append('<div id="foo" class="bar" style="color:black;" onclick="foobar()"></div>');
Your code's a little more complicated, because there's multiple levels (have you considered jQuery's click?):
$('#league2').append('<input type="button" id="2btn" value="1.2" class="butta" onmousedown="active('exam\'ple','awayteam')');

Escape Characters in JavaScript Function for Double quote

I have a web application where I am dynamically creating a url. The url has a parameter and I must pass a double quote. I have tried this all different ways but it is still not working. Anybody have any ideas?
To create the URL:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\"" + searchValue + "\"");
on the Page:
onClick="window.open('${surveyDetail.surveyInstructionsURL}')"
The result:
onClick="window.open('http://www.mytest.com/survey1.pdf#search="company"')"
The short answer is you need to double escape the double quotes. So you need:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\\\"" + searchValue + "\\\"");
which produces:
onClick="window.open('http://www.mytest.com/survey1.pdf#search=\"company\"')"
which will escape the quotes properly.
Couple of things to keep in mind:
This doesn't take care of double quotes in the search term itself. Make sure you escape that.
I'm not sure why you want to wrap the search term in double quotes. For a typical search url, you'll want a query string like: search=term not search="term" because you'll just end up stripping the quotes later. But maybe you need that for some reason.
I gather you're using PHP on the server side? In that case you should run the URL through htmlspecialchars() before concatenating it to the HTML.

Javascript in html - Using single quote inside another single quote

document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
The above code is my javascript. Problem is printing hello or any other string. If I just type 123 in place of hello, it does give alert. But am not able to use a string like hello there. Normally a string in an alert function is kept inside quotes ' ' but the entire content is inside double quotes and I have already used single quote at the beginning of onclick function. I tried using Escape character ("\") but it didnt help. Any suggestions?
Try this:
document.getElementById("img").innerHTML = '<img src="/sitepath/' + imgg + '.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
If you use apostrophes as delimiter for the HTML attributes, you have to HTML encode the apostrophes that you put inside the attribute:
document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
I prefer using apostrophes as string delimited in Javascript and quotation marks as delimiters for HTML attributes. Then you just escape the apostrophes that you have inside the Javascript string:
document.getElementById("img").innerHTML='< img src="/sitepath/'+imgg+'.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
To put any string inside a Javascript, inside an HTML attribute, inside a string in Javascript, you do:
escape any string delimiters in the string
HTML encode the Javascript code
escape any string delimiters in the HTML string
You have JavaScript inside HTML inside JavaScript. That's naturally confusing. Better to avoid the string-slinging problems of quoting and escaping (which, got wrong, can easily lead to security holes when user-submitted data is used), and do it the DOM way:
var img= new Image();
img.src= '/sitepath/'+imgg+'.jpg';
img.width= 72;
img.height= 44;
img.onclick= function() {
alert('hello');
};
document.getElementById('img').appendChild(img);
I tried using Escape character ("\") but it didnt help
Javascript is different from C#, you just use it twice at a time, example: alert('We are\\'t going to go')
It doesn't matter if your outer quotes are single or double. You can escape a character within an outer string with a backslash... \' becomes ' within the string itself. Either Darin's or Masood's example will work. But Masood is ignorant in reference to a need to use double-quotes as the outside enclosure.
what if someone needs to send a variable instead of a string "hello"? Something like this:
function showContent(toPopulate) {
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(*toPopulate*);'>show</a>"
}
function showOtherContent(toPopulate) {...}
so how to send toPopulate as a variable to showOtherContent()?
The above is solved like this:
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(\"" + toPopulate + "\");'>show</a>"
You will need to use the double quotes and escape it in the onclick attribute
document.getElementById("img").innerHTML="<img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick=\"alert('hello');\" />";

Using JavaScript single and double quotes for href's

I am having problem with escaping the single and double quotes inside the hrefs JavaScript function.
I have this JavaScript code inside href. It's like -
click this
Now, since double quotes inside double quote is not valid, I need to escape the inner double quotes for it to be treated as part of the string -
so, I need to do this -
click this
The problem is, even the above code is not working. The JavaScript code is getting truncated at -- myFunc(
I tried with the single quote variation too - but even that doesn't seem to work (meaning that if I have a single quote inside my string literal then the code gets truncated).
This is what I did with a single quote:
<a href = 'javascript:myFunc("fileDir/fileName.doc" , true)'> click this </a>
This works, but if I have a single quote inside the string then the code gets truncated in the same way as that of double quotes one.
Using backslashes to escape quotes is how it works in JavaScript, but you're not actually writing JavaScript code there: you're writing HTML. You can do it by using the HTML escaping method: character entities.
" // "
' // '
For example:
...
In case anyone needs to escape some thing like this:
<a href="www.google.com/search?q="how+to+escape+quotes+in+href""</a>
You can use ASCII code for double quotes %22:
<a href="www.google.com/search?q=%22how+to+escape+quotes+in+href%22"</a>
It is especially useful if you pass the link to JavaScript from PHP
As a general best practice, use double-quotes in HTML and single-quotes in JavaScript. That will solve most of your problems. If you need a single-quote in a JavaScript string, you can just escape it using \' - and you probably shouldn't be nesting literal strings any deeper than that.
As noted elsewhere, HTML entities are a possibility if the code is embedded in HTML. But you'll still have to deal with escaping quotes in strings in your JavaScript source files, so it's best to just have a consistent strategy for dealing with JavaScript.
If you are following this strategy and end up with a double-quote embedded in your JavaScript embedded in your HTML, just use the HTML entity ".
Normally, this kind of code is working without problems:
Click this
With this code, do you have any problem?

Categories

Resources