I need to read dot ner reesources string in java script as mention below.
var resources = #Html.ResourceStrings("Home_General_", Resources.ResourceManager);
The above line will render all the resources (from Dot net resource file) which start with resource key as "Home_General_"
Some of the values from the resources are like "Hi "XYZ" are you there" i.e The string contains quotes character.
If the string has quotes the above call fails.
The one way to avoid this problem is escape the special character as "Hi \"XYZ\" are you there"
Any other way where we can avoid this, As I don't want to pollute my resource string with lot of escape (\) characters.
You need to Javascript-escape any string when you render it as a Javascript string literal.
You must also remove the outer quotes from the string resource; that should be text, not a half-valid Javascript expression.
Use code like this to retrieve a single resource string:
var resourceXYZ = '#Html.Raw(HttpUtility.JavaScriptStringEncode(Resources.ResourceManager.GetString("Home_General_XYZ")))';
We do the following:
We get the resource string via Resources.ResourceManager.GetString().
We pass the result to HttpUtility.JavaScriptStringEncode to escape any special characters in JavaScript.
We pass the result to Html.Raw() to prevent Razor from applying HTML encoding on this string.
We then output the text enclosed in single quote quaracters into the page.
The function Html.ResourceStrings is not a standard function that is part of MVC. Someone at your place must have written it. If you show us this code, we could tell you how to rewrite it to return valid JavaScript literals.
You could wrap your #Html.ResourcesString(...) with HttpUtility.JavaScriptStringEncode which will handle all escape issues.
var resources = #HttpUtility.JavaScriptStringEncode(Html.ResourceStrings("Home_General_", Resources.ResourceManager));
Related
I should construct and pass following text in my JSON scheme. Here is how it should look:
r"""any-text-goes-here"""
Here is how I decided to construct it:
function make(text) {
return `r"""${text}"""`;
}
The function above takes any string and converts it to desired format. But, when I return it in my API as one of fields of JSON, it looks like following:
"r\"\"\"any-text-goes-here\"\"\""
I want to avoid backslashes. I understand that those slashes is needed by Javascript to properly work, but can I remove them, because client side awaits how I described above. Is it possible technically? How can I solve problem?
JSON strings are delimited by " characters.
" characters can be included in a JSON string only by using an escape sequence.
Escape sequences start with a \.
You can't avoid the backslashes.
See the grammar from the JSON website:
I need to concatenate untrusted* data into a javascript string, but I need it to work for all types of strings (single quoted, double quoted, or backtick quoted)
And ideally, I need it to work for multiple string types at once
I could use string replace, but this is usually a bad idea.
I was using JSON.stringify, but this only escapes double quotes, not single or backtick.
Other answers that I've found deal with escaping only a single type of quote at a time (and never backticks).
An example of what I need:
untrustedData = 'a String with \'single quotes\', \"double quotes\" and \`backticks\` in it';
const someJS = `console.log(\`the thing is "${escapingFunctionHere(untrustedString)}"\`)`
someJS will be passed to new Function
* N.B. In my context "untrusted" here doesn't mean potentially malicous, but it does need to cope with quotes, escapes and the like.
I am building javascript code dynamically, the constructed code will not be in any way web-facing. In fact its likely that I am the only one who will use this tool directly or indirectly.
I am happy to accept the minimal associated risks
NOTE TO OTHERS: Be sure you understand the risks before doing this kind of thing.
For those interested, I am writing a parser creator. Given an input ebnf grammar file, it will output a JS class that can be used to parse things.
I really do need to output code here.
If all you need to do is escape single quotes ', double quotes " and backticks `, then using replace to prepend a backslash \ should be enough:
untrustedData.replace(/['"`]/g, '\\$&')
const untrustedData = 'I \'am\' "a `string`"';
console.log(untrustedData);
const escapedData = untrustedData.replace(/['"`]/g, '\\$&');
console.log(escapedData);
On java (controller) i have a string that can contains an apostrophe. I send this string to the jsp page and the string is extracted on this way:
var intestatarioLibString = '${libretto.intestatarioLib};
(I send the object libretto wich contains the string).
The problem is the apostrophe, if the string contains an apostrophe, the string is "cutted" where the apostrophe is. Sample:
If the string that i send is 'DEL PIERO' ALESSANDRO' ,
when i open the jsp on browser i met an error because the debugger read like:
var intestatarioLibString = 'DEL PIETRO' ALESSANDRO
So, the apostrophe is considered the end of the string. The problem is that i CAN'T replace the apostrophe, i need it. Someone can give me a hand please?
You need to escape the characters in javascript string, for this you can use org.apache.commons.lang.StringEscapeUtils.escapeJavaScript.
You need to escape the string just try :
var intestatarioLibString = escape("DEL PIETRO' ALESSANDRO");
I want to add JSON data with the following string value:
json = "d:\xyz\abc";
This value is coming from a database at runtime. When I am going to display it in datatable, JSON formatting error is displayed. My requirement is that the above value will be displayed as it is in the datatable. Please help.
Escape it with another \:
var json = "d:\\xyz\\abc";
You'd better use a JSON library for your programming language. You don't retrieve database values directly with jquery, aren't you?
So, you'd use something like JSON.escape(my_string_from_db), or, in Ruby language I usually do my_string.to_json.
This will automatically escape everything that needs to be escaped.
Change to this:
json = "d:\\xyz\\abc";
See this question for further information
\ is the escape character in JavaScript strings, it gives special meaning to the character following the slash. Like \t is a tab character, \n is a new line. To put a backslash literal you'll need to use \\
The first backslash says the next character is going to be special, the following backslash says "oh, it's just a backslash."
I'm wanting to capture my search terms and pass them to a JavaScript variable, but I don't know how to handle quotes that might come through.
Here's what I have currently:
var searchTerms = "<!--#echo var="terms"-->";
var pattern = / /g;
newSearchTerms = searchTerms.replace(/[^a-zA-Z 0-9]+/g,'');
var searchStr=newSearchTerms.replace(pattern,"_");
I'm concerned that should "terms" contain double quotes (or an apostrophy if I use single quotes in the JS) then my function will fail.
How do I escape the string before it gets into script?
Thanks,
Steve
Edit/answer: I ended up doing this by moving this to an external script that captured and parsed the querystring rather than echoing it in the HTML.
If terms contains quotation marks, by the time you have done var searchTerms = "<!--#echo var="terms"-->"; it is already too late to replace any quotation marks, your JavaScript will be invalid. For example, if terms contains These are the "terms" your JavaScript would appear as follows (and produce a syntax error in the browser):
var searchTerms = "These are the "terms"";
If you are sure terms only contains double-quotes, you could do:
var searchTerms = '<!--#echo var="terms"-->';
If it could contain both single-quotes and double-quotes, you need to sanitize the output on the server using a server-side technology more sophisticated than <!--#echo var="..."-->.
From your code it looks like you're using Apache SSI includes. The echo SSI has an attribute called encoding which wil let you specify url-style encoding. You can encode quotes this way and simply unencode in Javascript with unescape()
Try this:
var terms = "<!--#echo encoding="url" var="terms"-->";
terms = unescape(terms)
i would add a javascript to the onchange event for the search textbox. capture the keystroke and ignore the quotes and any other special characters that might be entered. if the input is coming from the server side, then sanitize it before sending it to your script.