I have same input fields where the user inputs some data. Next my code converts it to JSON and send it to the server.
$("#submit").click(function(){
var inp = $("#inpTxt").val();
if(inp == null || inp == ""){
return;
}
jsonResult = JSON.parse('{"data": "' + inp + '"}');
$.ajax({
data : jsonResult,
...
});
});
The issue here is that sometimes the above code works and sometimes it just don't.
Most of the time I tested the code it worked like a charm but on productions I keep on getting the error reported several times.
I have not been able to figure out the possible cause yet.
Note: Some parts of the code are not shared in above but only part of what the problem seems to be.
As per the last comment the problem seems to be occurring when someone inputs some escape character in input (#Noob46 identified the case of using "Something" case but in my opinion it will also occur if any other escape character like \ or any other starting with \ may also cause the same problem).
Thus, one way to handle this is to filter the coming input string before passing it to JSON.parse.
To take things a step forward I have created some js that you can find here which in fact will let you handle the escape characters if they come as part of your input.
For further details refer to the attached code and example in the provided link here.
As the problem identified by me so let me also state an answer here. All you need is to add an additional \ before all the escape characters you encounter like:
\b : backspace
\f : form feed
\n : line feed
\r : carriage return
\t : horizontal tab
\v : vertical tab
" : double quote
\ : back slash
You can do so by code like:
inp = inp.replace('"','\\\"');
Or inp.replace('\','\\\\');
And so on for other characters.
When you use JSON.Parse function you need to handle special characters by your self. So if someone puts a " in your inpTxt input it will cause an error on parse that string.
You should do something like the code below to avoid parse error and let javascript correctly handle special characters on your string.
jsonResult = { data: inp };
I create a JS fiddle to make it easier to understand.
https://jsfiddle.net/ub3w0a8x/
Related
In my code, i need to pass the value present in instance variable to javascript, and then use that value to set onto textarea.
$('textarea.myclass').val('<%= #text_value %>');
But if the variable #text_value contains \n (this is\n demo) then, its leads to javascript error and the page shows exactly as this, separated by space in between,
$('textarea.myclass').val('this is
// error message over here
demo');
Any way i can handle this ?
I also faced such situation, and i just escaped the \ to \\, so finally \n to \\n, \r to \\r
$('textarea.myclass').val('<%= #text_value.gsub("\r","\\r").gsub("\n","\\n") %>');
Hope this corrects you error too.
The best answer I can come up with is to go for a variable. Without testing, this may be answer you are looking for:
var newline = "\n";
$('textarea.myclass').val('this is '+newline+' demo');
As SilverBlade suggested, maybe a double backslash would do the trick.
I've been working on my Safari extension for saving content to Instapaper and have been working on enhancing my title parsing for bookmarks. For example, an article that I recently saved has a tag that looks like this:
Report: Bing Users Disproportionately Affected By Malware Redirects | TechCrunch
I want to use the JavaScript in my Safari extension to remove all of the text after the pipe character so that I can make the final bookmark look neater once it is saved to Instapaper.
I've attempted the title parsing successfully in a couple of similar cases using blocks of code that look like this:
if(safari.application.activeBrowserWindow.activeTab.title.search(' - ') != -1) {
console.log(safari.application.activeBrowserWindow.activeTab.title);
console.log(safari.application.activeBrowserWindow.activeTab.title.search(' - '));
var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search(' - '));
console.log(parsedTitle);
};
I started getting thrown for a loop once I tried doing this same thing with the pipe character; however, since JavaScript uses it as a special character. I've tried several bits of code to try and solve this problem. The most recent looks like this (attempting to use regular expressions and escape the pipe character):
if(safari.application.activeBrowserWindow.activeTab.title.search('/\|') != -1) {
console.log(safari.application.activeBrowserWindow.activeTab.title);
console.log(safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
console.log(parsedTitle);
};
If anybody could give me a tip that works for this, your help would be greatly appreciated!
Your regex is malformed. It should be:
safari.application.activeBrowserWindow.activeTab.title.search(/\|/)
Note the lack of quotes; I'm using a regex literal here. Also, regex literals need to be bound by /.
Instead of searching and then replacing, you can simply do a replace with the following regex:
str = str.replace(/\|.*$/, "");
This will remove everything after the | character if it exists.
I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?
Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?
var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie
Somehow a cancel character (0x18) got into your string. You can simply replace it out with a regular expression.
var mystring='{"invis":"their brains process differently"}';
mystring = mystring.replace( /\x18/g, "" );
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
I found another JSON parser that doesnt crash with these hidden characters, it is located here:
https://github.com/douglascrockford/JSON-js
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.
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, "");