Replacing " with \" - javascript

I'm trying to replace all " with \" and parse string with JSON but browser throws an error SyntaxError: JSON Parse error: Unrecognized token '\'.
Below is code. String a is JSON.parsed well, but although I replace all " with \" in string b, so that it should be identical to string a, the parsing fails. I have the code in JSBIN.
var a = '[\"{\\"objects\\":[],\\"background\\":\\"#fff\\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]';
var b = '["{\"objects\":[],\"background\":\"#fff\"}","","","","","","","","",""]';
// Replace " with \"
// Charcode 92 is \
b = b.replace('"', String.fromCharCode(92)+'"', "g");
a = JSON.parse(a);
console.log(a);
b = JSON.parse(b);
console.log(b);
Any idea, how I could string b parsed with JSON.parse? If I replace all " with \" manually, it parses well, but I'm seeking automated way.

the point is using 2 \:
b = b.replace(/"/g,'\\"')
and the result is:
[\"{\"objects\":[],\"background\":\"#fff\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]
as #isherwood, has said:
To be more clear, the backslash is an escape character, so you need to
double it so there's an actual character behind the escape.

Try using this:
b = b.replace(/"(?=[^\{]*\})/g, '\\"');
This will replace all the " within braces to \".
The first string a becomes actually:
["{\"objects\":[],\"background\":\"#fff\"}","","","","","","","","",""]
And that's what you have to make b become, except that just after making the variable, it becomes:
["{"objects":[],"background":"#fff"}","","","","","","","","",""]
So you actually have to put some \ back where they should be.
But since you are trying to parse JSON, you might be better off with:
b = JSON.stringify(b);

Related

Getting substrings (strings with "") with Regex

I have a main string like this:
const mainString: string = `
let myStr: string = "Hello world";
function x() { }
let otherVar: number = 4;
let otherString: string = "Other string value";
// something else INSIDE the main string
`;
Now I need to format this main string, but substrings cause unwanted stuff, so I need to get them.
The regex I used until now was: /"([^"]*)"/g.
With it I would get e.g. ['"Hello world"', '"Other string value"'] (in the mainString context from above).
But having a "\"" inside one of these substring, would throw off my regex and give me the part from the beginning until the \" and then, if some other substring was used anywhere else, give me the real end of the substring " (falsly as a start symbol) until the start of the next substring...
One important thing: I have absolutly no control what so ever about anything before and beyont the "substring value".
What would be the correct regex for my usecase?
Try this one
"((\\"|[^"])*?)"
\\" - mean look for \"
| - or
*? - for no greedy
see: regex101

splitting of strings in javascript which involves backslash

How can we split the following tag to extract the substring "PDSGJ:IO.HJ".
var input = "\\initvalues\PDSGJ:IO.HJ~some" .
I tried the following:
var input = "\\initvalues\PDSGJ:IO.HJ~some";
var b = input.split('\\');
alert(b[1]);
Note: The format remains the same , \\,\, ~ format is same and mandatory for all strings .
But the problem is , I get the output as: initvaluesPDSGJ:IO.HJ~some.
I need '\' also because I need to further split and get the value.
Any other method is there to get the value?
You can use regular expressions:
var input = '\\initvalues\PDSGJ:IO.HJ~some',
b = input.match(/[A-Z]+:[A-Z]+.[A-Z]+~[a-z]+/);
console.log(b && b[0]);
The backslash is interpreted as an escape character. So you're gonna have to add another backslash for each backslash.
Then directly search for the last backslash and then slice the string:
var input = "\\\\initvalues\\PDSGJ:IO.HJ~some";
var index = input.lastIndexOf('\\');
var str = input.slice(index+1)
alert(str);
It is indeed correct, like the others already mentioned, that a backslash is interpreted as an escape character.
To output proper result, thus as a list.
var txt='\\\\initvalues\\PDSGJ:IO.HJ~some';
txt.split(/\\\\/).pop(0).split(/\\/)
(2) ["initvalues", "PDSGJ:IO.HJ~some"]

Space behind a backslash in a multiline string breaks the JavaScript code execution

Chrome version: Version 57.0.2987.110 (64-bit)
This is the error i get: "Uncaught SyntaxError: Invalid or unexpected token".
This is the code:
var x = "\
";
If i remove the space behind the backslash, everything works fine.
Why does this happen?
Because its an unterminated string literal.
The JavaScript parser takes a backslash at the end of an unclosed quotation as a line continuation of the string. But you can have backslashes inside strings, so if the backslash isn't the last character of the line, how is the parser supposed to infer that it means a line continuation?
For example:
// this is legit
var foo = "the path is C:\\Users\\bob";
// this too
var foo = "the path is \
C:\\Users\\bob";
// this is an error: unclosed quote, no continuation
var foo = "the path is C:\\Us
ers\\bob";
// your error case, altered slightly to clarify
var foo = "the path is\ C
:\\Users\\bob";
In the error cases the parser can't tell that backslash isn't part of a file path and was meant as a line continuation: it doesn't know what a file path is. It has no a priori knowledge of language, it has to be able to work with arbitrary sequences of characters. The fact that its whitespace doesn't matter, there's just no way for the parser to infer you meant it to continue the string on to the next line.
This is a frequent source of errors because you can't tell what the problem is by looking at the source code. As a less error prone alternative, you may use any of the following:
// concatenation
var foo = "the path is " +
"C:\\Users\\bob";
// Array.prototype.join
var foo = [
"the path is ",
"C:\\Users\\bob"
].join("");
// ES 6 template strings, note that whitespace is preserved
let foo = `
the path is
C:\\Users\\bob
`;
The \ character is used to convert special characters to literals.
For example \t will be converted to a tab space. There's a reference on special characters at the end of paragraph 8.4 of the ECMAScript specs.
As the note at the mentioned spec says, there's one notable exception: the newline character. It is not converted to its literal form and is instead essentially skipped. Think of it as the escape sequence for an empty string.
"abc\
def" === "abcdef"
This has the interesting side effect of letting you "format" your strings over multiple lines, purely for code aesthetics purposes.
In your specific case
var x = "\
";
will create a string with a space followed by a literal newline character, which is not a valid syntax.
var x = "\
";
will escape the newline and create an empty string, which is valid.

JavaScript parse function JSON.parse does not work as expected

The case:
var s = '{"a": 2}';
var d = JSON.parse(s); // d = Object {a: 2}
It is OK.
The similar case does not parse string, however. Why?
var s = "{'a': 2}";
var d= JSON.parse(s) // Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Expected result - parsed object like in the first case. It should have worked because ' and " are interchangeable in javascript.
According to the standard, you need double quotes to denotes a string, which a key is.
It should have worked because ' and " are interchangeable in javascript.
JSON is not JavaScript.
JSON strings must be delimited with quotation marks, not apostrophes.
See the specification:
A string begins and ends with quotation marks.

fix/escape javascript escape character?

see this answer for reasoning why / is escaped and what happens on nonspecial characters
I have a string that looks like this after parsing. This string comes fron a javascript line.
var="http:\/\/www.site.com\/user"
I grabbed the inside of the quote so all i have is http:\/\/www.site.com\/user. How do i properly escape the string? so its http://www.site.com/user? I am using .NET
Use the String.Replace() method:
string expr = #"http:\/\/www.site.com\/user"; // That's what you have.
expr = expr.Replace("\\/", "/"); // That's what you want.
That, or:
expr = expr.Replace(#"\/", "/");
Note that the above doesn't replace occurrences of \ with the empty string, just in case you have to support strings that contain other, legitimate backslashes. If you don't, you can write:
expr = expr.Replace("\\", "");
Or, if you prefer constants to literals:
expr = expr.Replace("\\", String.Empty);
I am not sure why it has the \ in it since var foo = "http://www.site.com/user"; is a valid string.
If the \ characters are meant to be there for some strange reason, than you need to double them up
var foo = "http:\\/\\/www.site.com\\/user";

Categories