I have jsp code as:
onclick="showURL('${result.url}')"
${result.url} is dynamic value. When an apostrophe comes in the URL I get the error.
I have tried all the methods like escape, encodeURI, replacing the single quotes with double but nothing works.
Script call is as follows:
function showURL(name){
alert(name);
}
<%#taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}
See: How can I escape special HTML characters in JSP?
You need to ensure that ${result.url} returns a valid URL. Quotes are invalid in URLs. It sounds like that you're returning an URL with a query string with unencoded parameters like follows
public String getUrl() {
return "page.jsp?foo=" + foo + "&bar=" + bar;
}
You need to change the method as follows
public String getUrl() {
return "page.jsp?foo=" + URLEncoder.encode(foo, "UTF-8") + "&bar=" + URLEncoder.encode(bar, "UTF-8");
}
You cannot fix this in the JavaScript side with escape(), etc. It's already too late then.
why not just do this:
onclick=showURL("${result.url}");
function showURL (result_url) {
alert("<c:out value='"+ result_url + "' />");
}
then you don't have to worry about escaping at all.
-tjw
Related
I am trying to pass this url in the String variable using HTML button within java but this is not working. Can someone help?
String URL = "http://localhost/asp"
out.append("<input type=\"button\" value=\"Refresh4\" onClick=\"window.location.reload(URL)\"/>");
Thanks
You need to concatenate the variable into the string with + URL +:
String URL = "http://localhost/asp";
out.append("<input type='button' value='Refresh4' onclick='window.location.reload(" + URL + ")'/>");
Also, no need to escape all the " you used. In Javascript, you can use '.
My problem is how to properly format string in javascript function parameter list. Function call is created on the server, problem is with string single apostrophes.
Code (.NET, C#) (I want only element.cMEST_CDO2 in single quotes):
#"ng-click='DeleteElementFromSession(" + element.iMERC_KEY + "," + element.iACCO_KEY +
#",'" + element.cMEST_CDO2 + #"');'></i></div>";
This code is on the client visible like this (it throws error):
I would like to be like this:
EDIT:
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
I am trying to directly write a Javascript variable assignment code on a ASP.NET web page.
Response.Write("<script>itHtml = '");
Response.Write("<div id=\"pop_ctrl\">Select</div><ul id=\"demo_ul\">");
foreach (Article a in arts)
{
Response.Write("<li class=\"demo_li\"><a onclick=\"ShowArticleCard(" + a.Id + ",\'" + a.User + "\',\'" + a.DateString + "\'); return false\"><div>" + it.User + "</div> <div>" + it.Title + "</div></a></li>");
}
Response.Write("</ul>");
Response.Write("';</script>");
Anchor tag in this markup executes a function ShowArticleCard() on click. This function accepts one int and two string parameters. When I am trying to add a C# string variable in place of string parameters, it replaces them like a JavaScript keyword. I tried using ',\' and \", but error persists. So, are there any levels of nested quotes we can use? If not how can I resolve this?
Try wrapping the actual value (parameter) in the quotes, like this,
onclick=\"ShowArticleCard(" + a.Id + ",'" +
a.User + "','" + a.DateString + "'); // Remaining code
Changed
I have removed the single quotes from the int type param, and removed the escape slash from the string types. They can be simply put as, '. Now when the code would run, it would be considered as a string. Otherwise (if the value is numeric) then ignore these quotes and enter them as they are. Only string-type data requires to be wrapped in either ' or ". In JavaScript they are same. In C#, ' and " have different meanings, you know that well.
Tip: Also, if you are writing something for client-side rendering, like in ASP.NET, you can easily write it as,
string.Format("<a href='{0}' onclick='func({1})'>My Link</a>",
hyperlink, param);
This would be rendered as you want it to be. :) The single quotes would be converted to double quotes once rendered in your browser. Or you can use # before the string, and write " inside the string without having to escape them.
I figured out a way of doing this. I don't know why it didn't came in my mind before.
I enclosed JavaScript function's string parameters with \\'. Like this:
ShowArticleCard(" + a.Id + ",\\'" + a.User + "\\',\\'" + a.DateString + "\\');
So that the resultant code will be:
ShowArticleCard(someid,\'someUser\',\'someDateString\');
Here, while calling a function displayCDinfo(), the syntax used is
document.write("<tr onclick='displayCDInfo(" + i + ")'>");
where i is the for loop counter.
However, the function declaration is given as
function displayCDInfo(i)
{
...
}
Why do they use displayCDinfo(" + i + ") instead of displayCDinfo(i) while calling the function? The code doesn't work when the "+ +" is removed.
The + operator is joining the variable's value to the string. Otherwise you are sending the letter i instead of what i contains.
It's all about the quotes. In the first instance, it's escaping the string to allow i to be sent as a variable instead of a character
Does JavaScript have a built-in function like PHP's addslashes (or addcslashes) function to add backslashes to characters that need escaping in a string?
For example, this:
This is a demo string with
'single-quotes' and "double-quotes".
...would become:
This is a demo string with
\'single-quotes\' and
\"double-quotes\".
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
A variation of the function provided by Paolo Bergantino that works directly on String:
String.prototype.addSlashes = function()
{
//no need to do (str+'') anymore because 'this' can only be a string
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
By adding the code above in your library you will be able to do:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
EDIT:
Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
Use encodeURI()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.
You can also use this
let str = "hello single ' double \" and slash \\ yippie";
let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));