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>";
Related
Why, when I change this function variable "endc" to normal text example
let endc = "here is path as string"
then is working - when I want to get "path" from function then my code is broken
there is my problem - why?
The + operator is overloaded for String class, so both the operand must be String for it to work.
Here your variable endc is type of URL. So the + doesn't work for String and URL.
Better to convert your URL into string and then use +, like this:
var welcome = js + endc.absoluteString + typer
Now, it should work.
Also, I think you should add your semicolon in the typer string itself.
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\');
I'm running a Node server that receives a plain utf8 text and parses the content to JSON. Part of the JSON will be the body of an HTML document.
The problem is that when the input has characters such as "รค" or " ' ", the HTML document gets all crazy. I guess it has to do with the coding/decoding of the parser for these special characters.
Any ideas regarding this ?
[EDIT]
The parsing and JSON object are basically this:
var string = <mail_body><html> html code here...<html><mail_body>
var mail_body = string.split("<mail_body>")[1]
var obj = {
"subject": "subject 123",
"mail_body": mail_body
}
You can use this for the "'"
var escapedText = text.replace(/\\'/g, "\\'");
and use a unicode for the "letter a with eyes"
like this -> \u2665
https://mathiasbynens.be/notes/javascript-escapes
The most important thing you need to do is to escape the incoming string to eliminate quotes that will break your JSON, which is the only significant problem I would expect to see with Node - browsers have a slightly harder time. From your input you're looking at something like this:
var string = <mail_body><html> html code here...<html><mail_body>
var mail_body = string.split("<mail_body>")[1]
mail_body = mail_body.replace(/\"/g, '\\"'); // regex for global replace, have to escape quotes
That should get you a mail body that doesn't unexpectedly end and break the rest of your JSON.
I want to add some strings to a textarea which are file basenames. Everything is fine, but the only problem is that it mixes all the values and there are not any line breaks:
var file_name = file.file_name;
var base = new String(file_name).substring(file_name.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1)
base = base.substring(0, base.lastIndexOf("."));
$('textarea#image_Basename').append(base).split('\n');
These are my file basenames:
5b0cd65710052633dc5dcac406a382c4
212asaddgcvjh622sdsds22113554dfd
5sd5weea55rr6qasfdjkloijhj665s6a
But after storing the data in to the database and retrieving it, the result I get is:
5b0cd65710052633dc5dcac406a382c4212asaddgcvjh622sdsds22113554dfd5sd5weea55rr6qasfdjkloijhj665s6a
To preserve newlines that are coming from a database or whatever, replace the newline characters with the HTML entity for a line feed:
base = base.replace("\n", '
');
$('#image_Basename').append(base);
If you're trying to append each string with a newline at the end, just concatenate it onto the string:
$('#image_Basename').append(base + '
');
Also, you're using split on the textarea jQuery element, which doesn't make sense as it is an object not a string.
My Special thanks to #rink.attendant.6, his second method worked for me :) The answer is:
$('#image_Basename').append(base + '
');
After adding this, I got all the file basenames in separate lines!
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