Using JavaScript single and double quotes for href's - javascript

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?

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

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

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.

Selecting element by unescaped data attribute

Without going into specifics why I'm doing this... (it should be encoded to begin with, but it's not for reasons outside my control)
Say I have a bit of HTML that looks like this
<tr data-path="files/kissjake's files"">...</tr> so the actual data-path is files/kissjake's files"
How do I go about selecting that <tr> by its data path?
The best I can currently do is when I bring the variables into JS and do any manipulation, I URLEncode it so that I'm always working with the encoded version. jQuery seems smart enough to determine the data-path properly so I'm not worried about that.
The problem is on one step of the code I need to read from a data-path of another location, and then compare them.
Actually selecting this <tr> is what's confusing me.
Here is my coffeescript
oldPriority = $("tr[data-path='#{path}']").attr('data-priority')
If I interpolate the URLEncoded version of the path, it doesn't find the TR. And I can't URLDecode it because then jQuery breaks as there are multiple ' and " conflicting in the path.
I need some way to select any <tr> that matches a particular data-attribute, even if its not encoded in the html to begin with
First, did you mean to have the extra " in there? You will have to escape that, as it's not valid HTML.
<tr data-path="files/kissjake's files"">...</tr>
To select it, you need to escape inside the selector. Here's an example of how that would look:
$("tr[data-path='files/kissjake\\'s files\"']")
Explanation:
\\' is used to escape the ' inside the CSS selector. Since ' is inside other single quotes, it must be escaped at the CSS level. The reason there are two slashes '\` is we must escape a slash so that it makes it into the selector string.
Simpler example: 'John\\'s' yields the string John\'s.
\" is used to escape the double quote which is contained inside the other double quotes. This one is being escaped on the JS level (not the CSS level), so only one slash is used because we don't need a slash to actually be inside the string contents.
Simpler example: 'Hello \"World\"' yields the string Hello "World".
Update
Since you don't have control over how the HTML is output, and you are doomed to deal with invalid HTML, that means the extra double quote should be ignored. So you can instead do:
$("tr[data-path='files/kissjake\\'s files']")
Just the \\' part to deal with the single quote. The extra double quote should be handled by the browser's lenient HTML parser.
Building off of #Nathan Wall's answer, this will select all <tr> tags with a data-path attribute on them.
$("tr[data-path]");

Error using Javascript and JSP, string with space gives `Unterminated string literal`

I have to pass a string value to JavaScript from JSP page.
I am using
display("<%=name%>")
It works fine but when i have string like 'sweet milk', JavaScript throws the error
Unterminated string literal
How to solve this?
Your string contains single quotes - you can escape single quotes as "\x27" and double quotes as "\x22" and then pass it to javascript.
You probably have characters in your String that should be escaped in Javascript. For example, if your string is My name is "John", your code will generate
var a = "My name is "John"";
which is invalid.
You should use StringEscapeUtils.escapeJavaScript from commons-lang to make sure everything is correctly escaped (single and double quotes, newlines, tabs, etc.).
I guess there's an error in the generated JavaScript code. Is there any way to look at you page? I suggest to look at the generated source code of that page.

Categories

Resources