How to allow user to input escaped chars in Javascript - javascript

A simple one here.
I have an HTML <textarea> in which I want to allow the user to enter escape sequence. I.e.:
Hello\nworld\x21
And I want my script to "interpret" the \n and the \x21 to get:
Hello
world!
Thanks
EDIT:
The purpose of this is to allow the user to enter thermal printer's code in an html page. The printer needs special chars. I want to take that string, "interpret" the special codes and send it to the printer. Currently, the printer prints the string as-is.

The only way I can think of that doesn't use a long replace line is with the eval() function. You could, for example, use the following:
function useEscapes(s) {
return eval('("' + s.replace(/([^\\]|^)(?=(\\\\)*["\n])/g, '$1\\').replace(/\n/g, 'n') + '")');
}
The replace is to make sure it's safe to pass into the eval() function.
EDIT 9/28/2016:
There's a better way that isn't a security risk. Because a string literal is valid JSON, you can wrap it in quotes and use JSON.parse. You can also possibly escape quotes in it so that users don't get inexplicable syntax errors. If an attacker tries to put code outside the string, it will just throw a syntax error.
function useEscapes(s) {
return JSON.parse('"' + s
.replace(/((^|[^\\])(\\\\)*)"/g, '$1\\\\"') // optional - prevents syntax errors
+ '"');
}

Related

Escape dotnet resources in javascript

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

How to combat the backslash return character breaking my javascript?

I have just realised that if a user enters a '\' into the input field, when I am trying access that value my javascript breaks due to the escape character.
What I wish to know is how I would get around this? I want my users to still be able to input a '\', I have tried using a regEX replace and other similar methods, but my code still breaks regardless (with no error mind you)
JavaScript:
var r = document.getElementById('r-box').value;
If the above contains a \, the code will just freeze.

How to handle possibly HTML encoded values in javascript

I have a situation where I'm not sure if the input I get is HTML encoded or not. How do I handle this? I also have jQuery available.
function someFunction(userInput){
$someJqueryElement.text(userInput);
}
// userInput "<script>" returns "<script>", which is fine
// userInput "<script>" returns &lt;script&gt;", which is bad
I could avoid escaping ampersands (&), but what are the risks in that? Any help is very much appreciated!
Important note: This user input is not in my control. It returns from a external service, and it is possible for someone to tamper with it and avoid the html escaping provided by that service itself.
You really need to make sure you avoid these situations as it introduces really difficult conditions to predict.
Try adding an additional variable input to the function.
function someFunction(userInput, isEncoded){
//Add some conditional logic based on isEncoded
$someJqueryElement.text(userInput);
}
If you look at products like fckEditor, you can choose to edit source or use the rich text editor. This prevents the need for automatic encoding detection.
If you are still insistent on automatically detecting html encoding characters, I would recommend using index of to verify that certain key phrases exist.
str.indexOf('<') !== -1
This example above will detect the < character.
~~~New text added after edit below this line.~~~
Finally, I would suggest looking at this answer. They suggest using the decode function and detecting lengths.
var string = "Your encoded & decoded string here"
function decode(str){
return decodeURIComponent(str).replace(/</g,'<').replace(/>/g,'>');
}
if(string.length == decode(string).length){
// The string does not contain any encoded html.
}else{
// The string contains encoded html.
}
Again, this still has the problem of a user faking out the process by entering those specially encoded characters, but that is what html encoding is. So it would be proper to assume html encoding as soon as one of these character sequences comes up.
You must always correctly encode untrusted input before concatenating it into a structured language like HTML.
Otherwise, you'll enable injection attacks like XSS.
If the input is supposed to contain HTML formatting, you should use a sanitizer library to strip all potentially unsafe tags & attributes.
You can also use the regex /<|>|&(?![a-z]+;) to check whether a string has any non-encoded characters; however, you cannot distinguish a string that has been encoded from an unencoded string that talks about encoding.

How to get a Clean String in Javascript?

i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.

html entity decode fail with the new lines in textareas

when I get a text from a textarea in html like this
wase&
;#101;m
the correct decode is waseem
notice the newline , when I decode it I get
wase&;#101;m
the newline make errors here , Can I fix it ? I use javascript in the decoding process .
I use this function in decoding
function html_entity_decode(str) {
var ta=document.createElement("textarea");
ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
return ta.value;
}
You could pass it through the following regex - Replace
&[\s\r\n]+;(?=#\d+;)
with
&
globally. Your HTML entity format is simply broken. Apart from the fact that HTML entities cannot contain whitespace and newlines, they cannot contain semi-colons in the middle.
Your input text may not be right and it is working as intended. Garbage-In-Garbage-Out.
I suspect the &\n; should be something else. But if not:
str.replace(/&\s*;/g, "");

Categories