escaped backslash coming out as "\\" in string - javascript

So while working on one of my first Node.js projects utilizing the file system I came across some behavior that stumped me. I had read that in JS when you need to put backslashes in a string you have to add an extra backslash to escape it. Even the text formatting on here on Stack Overflow is doing it correctly.
Example:
let str = "dir1\\file.txt" /* used two '\\' */
This made perfect sense to me. However when I print these strings to the console in Node.js they still appear to have that extra backslash still present. I did however test this on the browser console and it seems to be working fine. Why does this not work for Node.js? Does Node.js for some reason just not follow this JavaScript convention?
The personal project I've been working on has come to a complete stop for the past few days as a result of this confusion. So any clarity on this this would greatly help.

console.log functions give you debugging information. Different implementations of console.log are different. There is no standard which describes how they should represent a string.
Often they provide representations of strings that include escape characters in the visible output.
If you want to see the processed value of the string in Node, then write to STDOUT.
process.stdout.write("Your \\ string");

The string contains only one backslash regardless.
When you output a string in the Node.js console directly, it shows the string's contents. For example,
console.log("testing\\123");
outputs
testing\123
But when you output something like an object, Node.js shows a representation of that object, and in that representation, it shows the strings in string literal format. For example,
console.log({example: "testing\\123"});
outputs
{ example: 'testing\\123' }
Note the ' around the string literal, and the fact the backslash is escaped.
There's only one backslash there, it's just that it's showing you the string in string literal notation.
Browser consoles vary in how they show those two examples. For instance, Chrome's console shows them like this (at present, v72):
Chrome's console output for the second example is (to my mind) rather more confusing than Node.js's output, because although the string is shown in quotes, it's not a string literal. It's just the string contents. (I would much prefer it showed a string literal, or failing that, didn't show the string in quotes. What it does is a distant third choice in my view.)
This is purely a difference in how the consoles show the string. The string is the same in both cases: It has one backslash in it.

Related

Parse Javascript variables from String to JSON in React/Typescript

I want to read data embedded into a JavaScript-File with React-Native/Typescript. I'm reading the JS-File into a String and was playing around with regex but couldn't get this to work.
String:
SomeInfo=[{key:"some text with ;"}];SomeOtherInfo={56:23};SomeMoreInfo=7654321345;EvenMoreInfo=[{somekey:"some value"}];
The string itself is basically a one-liner. no line-breaks. whitespaces are only available in some values enclosed in double quotes (see above). The list of key-value pairs in the above example is not complete, so there might be more, always separated by ;.
I was able to use this regex
/([^=]+)=([^;]+)/gm
for a "generic" version to match key=value into groups but this does not work if the separator ; is part of any value (like in my example above).
With this regex:
/(?![SomeInfo=])(.*)(?=;SomeOtherInfo=)/gm
I am able to extract everything between those specific keys but then I am stuck with JSON.parse() as the keys are expected to be enclosed in quotes which is not the case.
How can I actually get all of those key-value pairs parsed as JSON?
Is it even possible to come up with a generic regex that also takes care of the quote issue of certain keys?
Any help appreciated, thanks!

Why I use JSON.stringify in safari and chrome to stringify a json get different result?

I just simply to use JSON.stringify({"a": "123"}) to stringify a json
In chrome, the " semicolon will not be escaped, it will echo
JSON.stringify({"a": "123"})
"{"a":"123"}"
But if I use the same code in safari, the " semicolon will be escaped, like this
JSON.stringify({"a": "123"})
"{\"a\":\"123\"}"
I want to know the reason about why the chrome and safari have the different result
It's not about JSON.stringify, it's about how the console displays value literals.
Safari chooses to make the entire line a valid literal. I.e. you could copy-paste the entire line into Javascript source code, and it'd be valid.
Chrome opts to just add decorative "" marks around the line to signify that it's a string value, but displays only the string contents as-is, without making it into a valid literal.
The advantage of Safari's method is that you can copy-paste values as code, while Chrome's advantage is that you can read a string's contents without needing to mentally parse it according to string escaping rules.

Escape characters in jQuery variables not working

I'm having issues with escaping characters (namely period) found in variables when using selectors in jQuery. I was going to type this all out, but it was just easier taking a screenshot of my console window in Chrome.
It looks like the variables and the clear text versions match up. I expect $('#'+escName) to return the div, just like $('#jeffrey\\.lamb') returns a div. It does not. Why?
You have to think in terms of the individual parsers that will be examining your string values. The very first one, of course, is the JavaScript parser itself. Backslash characters have a meaning in the string grammar, so if you want a single backslash in a string it needs to be doubled.
After the string is parsed from the source code into an internal string value, the next thing that'll pay attention to its contents (in this case) is the CSS selector evaluator (either Sizzle or the native querySelector code; not sure which in the case of strings with escapes like this). That code only needs one backslash to quote the . in order that it not be interpreted as introducing a class name match.
Thus, escName = "jeffrey\\.lamb"; is all you need in this case.

JavaScript JSON parser that tells error position

I've been having some troubles with parsing JSON that is received with WebSocket (original question - Parse JSON received with WebSocket results in error). The JSON string itself is valid (tested with several JSON validators), but JSON.parse throws an exception. I am trying to figure out what is it exactly that it cannot parse, but the only thing I'm getting is "SyntaxError: unexpected_token ILLEGAL", it doesn't say where is the exact position of the failed token. Is there any way of extracting such information?
Update: If I copy-paste that JSON string to a static file (e.g. "data.json") and then retrieve it and parse it with the same function (JSON.parse) - then it works fine.
So I'm assuming there's something tricky going on, I thought of newline symbol (may be there was \n instead of \r\n or vice versa) but completely removing all the line breaks didn't help. I would think that it very well may be an encoding problem, but the data is received via websocket and according to documentation it's utf-8 string.
2nd Update: IT WORKS just fine if I use "json_parse" from here: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
Then it works fine! Does that mean this is a bug in "JSON.parse" implementation used by Chrome or what?
Thank you.
You could copy an implementation of JSON.parse() from somewhere (like out of jQuery), change it's name so you can call it directly, tweak the implementation so that it never detects the built-in parser so it always uses the JS parser and then change your code to use the new JS version of the parser, then trace through it in a javascript debugger until you find what it doesn't like.
One thing to check is if you have quotes and slashes within your JSON string. If yes, they need to be escaped:
{
"key": "i've \"quotes\" in me",
"key2": "and \\slashes too"
}
Also, JSONLint gives you the exact location of the error.
As per JSON.org, you cannot have quotes and slashes in your strings, so you need to escape them.
I think you don't need to call JSON.parse:
JSON.parse({"key": "whatever"}) // Syntax Error ILLEGAL
because it's already an object. I would also be curious to see the result of the following code:
eval("(" + json + ")");
Or
JSON.parse(decodeURIComponent(json));
Can't tell much with the details, but the possibility may be that your validator is doing non-strict parsing and your javascript may be doing strict parsing...

Finding beginning and end quotations

I'm starting to write a code syntax highlighter in JavaScript, and I want to highlight text that is in quotes (both "s and 's) in a certain color. I need it be able to not be messed up by one of one type of quote being in the middle of a pair of the other quotes as well, but i'm really not sure where to even start. I'm not sure how I should go about finding the quotes and then finding the correct end quote.
Unless you're doing this for the challenge, have a look at Google Code Prettify.
For your problem, you could read up on parsing (and lexers) at Wikipedia. It's a huge topic and you'll find that you'll come upon bigger problems than parsing strings.
To start, you could use regular expressions (although they rarely have the accuracy of a true lexer.) A typical regular expression for matching a string is:
/"(?:[^"\\]+|\\.)*"/
And then the same for ' instead of ".
Otherwise, for a character-by-character parser, you would set some kind of state that you're in a string once you hit ", then when you hit " that is not preceded by an uneven amount of backslashes (an even amount of backslashes would escape eachother), you exit the string.
You can find quotes using regular expressions but if you're writing a syntax highlighter then the only reliable way is to step through the code, character by character, and decide what to do from there.
E.g. of a Regex
/("|')((?:\\\1|.)+?)\1/g
(matches "this" and 'this' and "thi\"s")
use stack.. if unmatched quote found push it.. if match found pop
I did it with a single regular expression in php using backwards references. JS does not support it and i think that's what you need if you really want to detect undefined backslashes.

Categories