Javascript .replace() of the character " with the characters \" - javascript

I am trying to pass a JSON string to a C# .exe as a command line argument, from Javascript as a node.js child-process. For the sake of argument my JSON looks something like this:
string jsonString = '{"name":"Tim"}'
The issue with passing this as a C# arg is that the double quotation marks must be retained if I hope to parse it in the C# code. As such, what I need to pass into the C# command line needs to look something like this, where I escape the double quotation mark:
string jsonStringEscaped = '{\"name\":\"Tim\"}'
The motivation for doing this is that it allows me to maintain a consistent object structure across the two languages, which is obviously highly desirable for me.
In order to achieve this, I am attempting to use the Javascript .replace() method prior to sending the argument to the C#, and to do this I use a simple RegEx:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\"")
Unfortunately, this returns something of the form '{\\"name\\":\\"Tim\\"}' which is useless to me.
I have tried variations on this:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\ \"")
\\ returns '{\\ "name\\ ":\\ "Tim\\ "}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\\")
\\ returns '{\\\\name\\\\:\\\\Tim\\\\}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\")
\\ is invalid
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\ ")
\\ returns '{\\ name\\ :\\ Tim\\ }'
I have tried variations where the second .replace() argument is contained within single quotation marks '' rather than double quotation marks "" with no success.
Can anyone tell me what I am doing wrong? Better yet, can anyone suggest a more efficient method for doing what I am trying to achieve?

Unless I'm misreading you, I think you're just trying to escape a character that doesn't need to be escaped in your regex (").
var jsonString = '{"name":"Tim"}'
var escaped = jsonString.replace(/"/g, '\\"');
// escaped == "{\"name\":\"Tim\"}"

Related

Single quotes not being replaced in javascript?

I'm trying to sanitize quotes from a text input. Right now my code is:
string = string.replace(/'/g, '\'');
string = string.replace(/"/g, '\"');
My out put has all double quotes replaced, but the single quotes remain. I am fairly confident in my regex, and haven't had a problem with the replace function before. Is there a chance that mySQLdb is messing this up? I am posting it and then getting almost immediately after. This seems like such a simple issue but it really has me stumped
Your replacements are null operations since the backslash is consumed by the string literal itself and is not present in the actual string value.
Instead escape the backslash to really get one in your string:
string = string.replace(/'/g, "\\'");
string = string.replace(/"/g, '\\"');
You can of course do this in one operation:
string = string.replace(/(['"])/g, "\\$1");

store arbitrary JavaScript code into a string variable

I have a program (written in Clojure) that injects some JS code into a JS function, then evaluates it via Nashorn. I have no control over the code passes (it may contain quotes, simple quotes...).
It looks like this :
;; Clojure
(eval-str (str "print(evaluateCode(\"" s " \"))"))
// equivalent code in pseudo-js just for those not reading Clojure fluently
evalJS("println(evaluateCode(" + arbitraryJS + "))")
The evaluateCode function is already loaded.
// already loaded in Nashorn
function evaluateCode(code) {
// do something with the code
//...
eval(code);
}
This works fine for simple programs, ex. if arbitraryJS = "var a=123; print(a); return a;".
But as soon as the program contains quotes, it breaks. ex. "var a = 123; print("a is now", a);"
Note : the actual code is there.
You need to escape the string. place a \ before every ".
If you need the \ itself use it double \\
Sorry, I am not allowed to comment yet... :/
I would suggest to escape the quotes and backslashes. I would go for single quotes as JS string delimiters, as in Clojure you are bound to use double quotes for delimiting strings:
;; Clojure
(eval-str (str "print(evaluateCode('"
(clojure.string/replace s #"(['\\\\])" "\\\\$1")
"'))"))
The find and replace patterns each have four backslashes. As in Clojure backslash is an escape character, they actually denote only two backslashes. In regular expressions backslash is also an escape character, so in the end they just denote one, literal backslash each. So this means "prefix any occurrence of backslash or quote with a backslash."
You shouldn't worry about comments and templates and such, as the escape characters only exist in Clojure (after the replace), but are resolved the moment the complete string is parsed by the Javascript engine. The evaluateCode function will never see the escape characters, but the plain value of s.
Example
;; Clojure
(def s "a = 'test'; // 'test' used here")
(eval-str (str "print(evaluateCode('"
(clojure.string/replace s #"(['\\\\])" "\\\\$1")
"'))"))
This will evaluate to:
(eval-str "print(evaluateCode('a = \\'test\\'; // \\'test\\' used here'))")
Note that the backslashes are doubled in the above representation, but that is because Clojure needs that. The actual string only has single occurrences of the backslashes. If instead of calling eval-str, you would call println with the same argument, you would get this output:
print(evaluateCode('a = \'test\'; // \'test\' used here'))
That is the string interpreted by the Javascript engine, and so it interprets the backslashes as escape characters, passing the clean string to evaluateCode.
So if evaluateCode looked like this:
function evaluateCode(code) {
alert(code);
}
It would produce this alert:
a = 'test'; // 'test' used here
So, the escaping backslashes are not there at all in Javascript. It will see the exact same value as the Clojure symbol s represents.
In the after end I used the Apache Commons Lang StringUtils since the other solutions did not work. See it here.

Why can't Javascript parse this JSON array from a string literal?

What I am trying to do is simple. Parse this array holding json objects into a Javascript array.
var merchantsJson = JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]');
But the unicode character \u003C seems to be breaking the parser. In the chrome console I see "Uncaught SyntaxError: Unexpected token <"
A little more info. The above is what the code is evaluated to. In reality the code contains a jsp expression.
var merchantsJson = JSON.parse('${jsonArr}');
If I remove the single quotes, there is no issue, but eclipse give me an "missing semicolon" error message. Is it possible to parse the array with the quotes as I am trying to do?
The interpolation of ${jsonArr} is already a JavaScript object. When you wrap it in '${jsonArr}' this turns it into a string and you have to use JSON.parse.
There's no need to make it a string. You can just do var merchantsArray = ${jsonArr}. JSON constructs are already interoperable with JavaScript code.
Because there's an extra " in your string literal that is encoded by \u0022:
> '[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]'
[{"id":61693,"name":"Más"},{"id":61690,"name":"'"</div>"}]
In short, your JSON in the string is invalid. You would need to escape the unicode escape sequences for the quotes in the string literal ("'\u0022</div>"), by using
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\u0022\u003C/div\u003E"}]'
// ^
or escape the quote character ("'\"</div>"):
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\\u0022\u003C/div\u003E"}]');
// ^^
However, there actually is no need to use JSON at all. Just output a JS array literal into your code:
var merchantsJson = ${jsonArr};
Try to replace \u with \\u. If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.
It's not because of \u003C, rather the \u0022 character is causing the issue, since it's a quotation mark and JavaScript treats it literally ending the string.
You need to escape that character: \\u0022 .
you have to use special character in your JSON string, you can escape it using \ character.
you need to replace \ with \\.
[{\"id\":61693,\"name\":\"Más\"},{\"id\":61690,\"name\":\"\\u0027\\u0022\\u003C/div\\u003E\"}]

How to find out if a given string is HTML Escaped or not?

Is there any method to find out if the given string is HTML Escaped or not?
Consider the following javascript code:
<script>
var str="hello";
var str_esc=escape(str);
document.write(isHTMLEscaped(str)) // *Should print False*
document.write(isHTMLEscaped(str_esc)); // *Should print True*
</script>
Is there any method equivalent to isHTMLEscaped in the above case?
I found that using
escape(unescape(str))
will always provide an escaped string. And the unescape string will do nothing unless the string itself contains escaped expressions.
Note: should have used encodeURI(decodeURI(str)) instead as escape is now depreciated.
As "hello"==escape("hello"), no, you can't at all guess if escaping was applied.
If you want to know if it's probable that the string has been escaped, then you might test
var wasProbablyEscaped = /%\d\d/.test(str);
var wasProbablyNotEscaped = !wasProbablyEscaped && /%\d\d/.test(escape(str));
as escaping adds % followed by two digits when something has to be escaped. But you can't be totally sure as some strings don't change when you escape them.
In your case, I'd probably advise you not to escape if wasProbablyEscaped is true.

Json String with comment out quotes in variable

I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example
"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]
\ is an escape character. try \\
If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';
I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/

Categories