escape special characters in javascript (jquery) function - javascript

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

Related

escape single quote in a string and pass this string value to java script function

I have a requirement where I have to escape single quote in a string and pass this string value to java script function
Ex: Mario O'Brian
<a href="javascript:goToMethod('<c:out value={myName"}/>'}
function goToMethod(myName){}
problem is I am not able to remove single quote . I tried using fn:replace tag but it has got its own limitations. fn tag is not working as expected in Websphere.Can you suggest me some alternative?
Thanks in Advance.
To escape
myName.replace(/'/g, "\\'"); // escaping \ with \, so used 2x
To remove
myName.replace(/'/g, "");

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("'","\\'");

How to write quotation marks in 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.

Passing an object-string to a javascript-function

I'm trying to pass a string like this:
{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}
to a javascript-function like this:
<a href="#" onClick="myFunction(myString);">
but can't get the escaping right. Is there a way to pass that object-string to a function or do I need to convert something?
Greetings,
Select0r
try:
var myString = '{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}';
EDIT:
In light of your recent comment I went back to the browser and tried this (works for me):
<a href="#" onClick="myFunction({'key':['value'],'key2':undefined,'key3':undefined,'key4':undefined,'key5':'value'});">
The change means that it's no longer longer passed as a string but as an object parameter to myFunction.
As Naeem said, you can enclose the string in a single quote. The difference between the single and double quote is this:
single quotes:
Can contain double quotes without stopping string
Cannot contain characters such as break lines
Can contain single quotes via \'
double quotes:
Can contain single quotes without stopping string
Can contain break line and other special characters
Can contain double quotes via \"
I found a solution, Naeem Sarfraz put me on the right track - it's not going to win a beauty contest, but it works:
As I can execute PHP in the context I'm in (but IE6 would ignore Javascript), I did a couple of replacements on single/double quotes with PHP.
$data = stripslashes(unserialize($data));
$data = addcslashes($data, "'");
$data = str_replace('"', "'", $data);
This will strip all slashes, add slashes for single quotes only and finally replace double quotes with single ones.
Now myString is in a state that can be passed to a Javascript function in onclick without quote-conflicts:
<a href="#" onClick="myFunction(<?php print $data; ?>);">
Thanks for your contributions!
If you can generate code just before this <a> element, you can try this:
<script type="text/javascript">
var myObj = {"key":["value"], "key2":undefined, "key3":undefined, "key4":undefined, "key5":"value"};
</script>
<a href="#" onClick="myFunction(myObj)">

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');\" />";

Categories

Resources