How to write quotation marks in JavaScript - javascript

Hi I want to do the following, but don't know how to write the quotation marks
allSearchResults[0]="<li> CXS101289/</li>";
It shall be quotation marks where the currently are.

Two ways times two
mix single and double quotes:
// single outside, double inside quotes
allSearchResults[0] = '<li>CXS101289/</li>';
or
// double outside, single inside quotes
allSearchResults[0] = "<li><a href='CXS101289/'>CXS101289/</a></li>";
use one set of quotes but escape inside ones:
// double escaped quotes
allSearchResults[0] = "<li>CXS101289/</li>";
or
// single escaped quotes
allSearchResults[0] = '<li><a href=\'CXS101289/\'>CXS101289/</a></li>';
First approach with mixing is usually easier, because it presents less work since you only have to change the opening and closing quote.

Just escape the quotes inside the a tag.
allSearchResults[0]="<li> CXS101289/</li>";

you can escape them like:
allSearchResults[0]="<li> CXS101289/</li>";
or use the other quotes :
allSearchResults[0]="<li><a href='CXS101289/'> CXS101289/</a></li>";

allSearchResults[0]="<li><a href='CXS101289/'> CXS101289/</a></li>";
or
allSearchResults[0]='<li> CXS101289/</li>';
or
allSearchResults[0]="<li> CXS101289/</li>";

Another, newer and very nice method: Use "multiline strings"!
Writing it like this, with a backtick at the beginning and end of the string, you can use anything you like inside, and even make use of variable substitution:
let b = "myvar value";
let x = `
<li class="myclass" onclick="myFunc('${b}')">
${b}
</li>
`;
That case is hard to do otherwise, mixing quotation marks within the string.

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

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.

Single quote JSP to JavaScript function

I have a string that must be used to be passed into a JavaScript function. I have tried many ways, but I still cannot make it to work.
<%=name%>
The name field is a string that contains single quotes such as It's Morning. I have tried to use:
String nameString = rs.getString("name");
nameString = nameString.replaceAll("'","\'");
<%=nameString%>
And also
nameString = URLEncoder.encode(nameString);
And also
nameString = nameString.replaceAll("'","'");
And also
nameString = nameString.replaceAll("'","&apos;");
I still cannot get it to work. And also I can't go for EL.
If you want to replace a single quote (') in a String with a JavaScript-escaped (backslashed) single quote (\') in Java code then you need to escape the backslash character (with a backslash!). For example:
nameString = nameString.replaceAll("'","\\'");
See also: String.replaceAll single backslashes with double backslashes
Try to use String.fromCharCode(39) instead of single quote, String.fromCharCode(39) is ASCII codes for single quote.
If you are doing it inside JSP tag, you need to have sufficient backslashes for one of them to actually make it into the web page. The code would be:
<%=nameString%>
You need one backslash to escape the other backslash and each of those needs to be escaped - hence four backslashes (yuck).
Hope that helps.
The following worked for me, as the HTML encoding is done before the function call and replaced the single quote with '.
nameString = nameString.replaceAll("'","\\'");

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')');

javascript string difference [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
single quotes versus double quotes in js
When to Use Double or Single Quotes in JavaScript
What is the difference (if any) between the javascript strings defined below?
var str1 = "Somestring";
var str2 = 'Somestring';
"" and '' mean two very different things to me predominantly writing code in C++ :-)
EDIT: If there is no difference why are there two ways of achieving the same thing and which is considered better practice to use and why. Thanks!
Javascript treats single and double quotes as string delimiters.
If you use single quotes, you can use double quotes inside the string without escaping them.
If you use double quotes, you can use single quotes inside the string without escaping them.
Both examples evaluate to the same thing.
alert(str1 == str2); // true
alert(str1 === str2); // true
Why two ways? Due to the way javascript allows you to mix the two, you can write html attributes out without messy escapes:
var htmlString1 = "<a href='#'>link</a>";
var htmlString2 = 'link';
As for best practice, there is no convention. Use what feels best.
Personally, I like making sure the Javascript I emit matches the HTML (if I double quote attributes, I will delimit JS string with a ', so emitted attributes will use ").
In Javascript a string is a sequence of zero or more Unicode characters enclosed within single or double quotes (' or "). Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes.
In client-side JavaScript programming, JavaScript code often contains strings of HTML code, and HTML code often contains strings of JavaScript code. Like JavaScript, HTML uses either single or double quotes to delimit its strings. Thus, when combining JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the other style for HTML.
No difference at all.
I believe the answer is there is no difference. They are both strings.
Here would be the usage of '
var mynewhtml = '<body class="myclass" ></body>';
or using "
var mynewhtml = "<body class='myclass' ></body>";
this also works but IMO is harder to read
var mynewhtml = "<body class=\"myclass\" ></body>";

Categories

Resources