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
Related
I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley
txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");
Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.
txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");
Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.
txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");
The above ensures that :// is not matched by doing a negative-lookahead.
There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.
The second line should read:
txt.replace(/:\//g,"<img src='img/smiley.gif'>");
/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).
The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.
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.
through queries to a Database I am retrieving such data that I previously inserted through HTML textarea or input. When I get the response from my DB , in a JSON object the text field looks like this :
obj : {
text : [some_text] ↵ [some_text]
}
I tried to replace with this function :
string_convert = function(string){
return string.replace("↵",'<br>')
.replace('&crarr','<br>')
.replace('/[\n\r]/g','<br>');
}
I have to show this string in HTML ,but it does not seems to work. I'm using UTF-8
Any advice?
The problem you have is that you have enclosed your regex in quotes. This is incorrect.
.replace('/[\n\r]/g','<br>');
^ ^
remove these two quotes
The quotes are unnecessary because the regex is already delimited by the slashes.
By putting quotes in there, you've actually told it that you want to replace a fixed string rather than a regular expression. The fixed string may look like an expression, but with the quotes, it will just be seen as a plain string.
Remove the quotes and it will be seen as an expression, and it will work just fine.
One other thing, though -- in order to make your regex work perfectly, I'd also suggest modifying it slightly. As it stands, it will just replace all the \n and \r characters with <br>. But in some cases, they may come together as a \r\n pair. This should be a single line break, but your expression will replace it with two <br>s.
You could use an expression like this instead:
/\r\n|\n|\r/g
Hope that helps.
you are missing the ending semicolons ; in your code:
string_convert = function(aString){
return aString.replace("↵",'<br>').replace('↵','<br>');
}
this does not necessary solve your problem, but it could likely.
From: Trying to translate a carriage return into a html tag in Javascript?
text = text.replace(/(\r\n|\n|\r)/g,"<br />");
I need to show the name of the currently selected file (in <input type="file"> element).
Everything is fine, the only problem is I'm getting this kind of string "C:\fakepath
\typog_rules.pdf" (browset automatically puts this as value for the input element).
When I try to split the string by '\' or '\\' it fails because of unescaped slashes. Attempts to match/replace slashes fails too. Is there a way around this? I need this to work at least in Opera and IE (because in other browsers I can use FileReader)
E.G. I'm getting "C:\fakepath\typog_rules.pdf" as input and want to get "typog_rules.pdf" as output.
For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.
This question already mentions, and links to other Stack Overflow questions regarding this topic.
Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.
string = string.split("\\");
In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.
So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.
Escape the backslash character.
foo.split('\\')
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
Slightly hacky, but it works:
const input = '\text';
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();
console.log({ input, output });
// { input: '\text', output: '\\text' }
Add an input id to the element and do something like that:
document.getElementById('inputId').value.split(/[\\$]/).pop()
In Javascript, when I put a backslash in some variables like:
var ttt = "aa ///\\\";
var ttt = "aa ///\";
Javascript shows an error.
If I try to restrict user in entering this character, I also get an error:
(("aaa ///\\\").indexOf('"') != -1)
Restricting backslashes from user input is not a good strategy, because you have to show an annoying message to the user.
Why am I getting an error with backslash?
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.
Just remember, for each backslash you want to output, you need to give Javascript two.
You may want to try the following, which is more or less the standard way to escape user input:
function stringEscape(s) {
return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}
This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.
You have to escape each \ to be \\:
var ttt = "aa ///\\\\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
because you had to show a message to user that user can't give a name which has (\) character.
I think the scenario is like:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.
If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
If you want to simulate, you code must be valid at first place.
var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used [] to quote text to be shown, so it would be less confused than using "".
The backslash \ is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
If you want to use special character in javascript variable value, Escape Character (\) is required.
Backslash in your example is special character, too.
So you should do something like this,
var ttt = "aa ///\\\\\\"; // --> ///\\\
or
var ttt = "aa ///\\"; // --> ///\
But Escape Character not require for user input.
When you press / in prompt box or input field then submit, that means single /.