Is it possible to replace these single quotes with double quotes? - javascript

I'm having some trouble trying to replace the single quotes ('...') with double quotes("...") in the following piece of code:
<img id="image" src="images/bird.jpg" onmouseover="PlaySound('mySound'); this.src='images/bird_second_frame.jpg'"
onmouseout="StopSound('mySound'); this.src='images/bird.jpg'">
Whenever I attempt to replace the single quotes with doubles, the code breaks, and I can't seem to find a different solution. I've been told not to use single quotes at all - is this an exception?
Any help is appreciated.

You can't use a literal " inside an HTML attribute value delimited by " characters. It will terminate the attribute value prematurely.
You can include one as ", but that would make the code significantly harder to read.
<img id="image" src="images/bird.jpg" onmouseover="PlaySound("mySound"); this.src="images/bird_second_frame.jpg"" onmouseout="StopSound("mySound"); this.src="images/bird.jpg"">
I've been told not to use single quotes at all - is this an exception?
No. You've just been given bad advice.
JavaScript and HTML don't distinguish between ' and " except when determining which characters can appear between them without being escaped.
Using ' in your example is simply more readable.
A better approach would be to avoid inline JavaScript entirely though.
<img id="image"
src="images/bird.jpg"
data-sound="mySound"
data-frame="images/bird_second_frame.jpg">
<script>
var element = document.getElementById("image");
element.addEventListener("onmouseover", play);
element.addEventListener("onmouseover", stop);
function play() {
PlaySound(this.dataset.sound);
this.dataset.original = this.src;
this.src = this.dataset.frame;
}
function stop() {
StopSound(this.dataset.sound);
this.src = this.dataset.original;
}
</script>

You can't use double quotes inside of a string that's bounded by double quotes because they would end the string.
Your use of single quotes looks appropriate in this case.

You can use single quotes freely in JavaScript; they're syntactically equivalent to double-quote characters (though any single string constant must be bound by the same kind of quote). That goes for HTML too, so you can get double quotes in your JavaScript by using single quotes for the attribute value delimiters:
<button onclick='alert("Hello World")'>Click Me</button>
However if you really want double quotes everywhere, you can escape them as HTML entities:
<button onclick="alert("Hello World")">Click Me</button>
That's pretty ugly but it works: the HTML parser is specifically looking for quote characters.
The best thing to do is to stop embedding your JavaScript event handler setup in your HTML and do it purely with JavaScript.

Related

Despite single quotes being encoded using htmlspecialchars, JavaScript is still complaining that these quotes need to be escaped in the function call

Something strange is occurring and I'm stumped.
I have a link that looks basically like this:
Link
As you can see, I'm calling function uploadVariantPicture with parameter "size:'test2&#039".
However, when I actually click the link, JavaScript complains that the two encoded single quotes aren't being escaped. I'm getting the following error:
SyntaxError: Unexpected identifier 'test2'. Expected ')' to end an argument list.
If I decode the two encoded single quotes and escape them using a backslash, then the function call succeeds. But the problem is I need it encoded. I cannot leave it unencoded and escape the quotes. This won't work for my situation.
Any help is greatly appreciated. I'm super confused.
HTML character entities and escapes are replaced by the HTML parser when parsing source. For quotation marks, it allows inclusion of the same kind of quotation mark in an HTML attribute that is being used to quote the attribute value in source.
E.G.
<element attribute=""">
<element attribute='''>
in source would produce attribute values of " (double quote) and ' (single quote) respectively, despite being the delimters used to quote the attribute value in HTML source.
Hence
Link
will produce an href attribute value of
javascript:uploadVariantPicture('size:'test'');
after removal of the outer double quotes by the HTML parser.
Options could include escaping double quotes (HTML ") inside the href value appropriately (it depends on the syntax accepted by uploadVariantPicture), including backslash escapes before the single quotes as mentioned in the post, or not using the javascript: pseudo protocol at all, in favor of adding an event listener in JavaScript.
Not using javascript: pseudo protocol is highly recommended - basically it's a hold over from HTML3.
Consider attaching an event handler properly using JavaScript instead so you don't have to worry about escaping issues, and so that you don't have to rely on the pollution of the global object for the script to work:
const uploadVariantPicture = (arg) => console.log(arg);
document.querySelector('a').addEventListener('click', () => {
uploadVariantPicture("size:'test2'");
});
<a>Link</a>
I can't think of any situations in which an inline handler would be preferable to addEventListener, unless you were deliberately trying to exploit an XSS vulnerability.

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

Javascript with Special Chartecter

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

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