I have an encoded string and I want to set it in a hidden field using javascript but I get 'Uncaught SyntaxError: Unexpected token ILLEGAL'
I can't replace these illegal characters with anything because I use them for decoding
string example
"wcdkH~`pnVAvIAzB?pAmA?Q?aBCiEi#yCEc#Iy#Ue#Iw#AkBCg#?GGi#G]Ga#SQOQSg#cAMM]W_#Qc#Ic#AcADIHaDCeCCkAAg#I[Qw#m#iAiAkBcBg#tAiAdDoKgLq#m#sC{B[E?f#AzIElEIxC[jJcAtRc#lEWhA[|#c#l#i#`#[NWDi#Bo#G_AOw#As#?WB]HKFm#h#Y\\U`#g#|AO~#E~##~#F~#XvAPh#Vf#f#t#l#p#|#~#x#`Ab#t#\\x#T|#PbAZlCLn#RpBl#fGd#fEI|AId#Q^QZqCZyBLoB]iDwAgAq#u#]iCqAoB[c#AwHmAgAG{#BmA^e#Ta#^WVg#p#]n#qFvLsGvNSl#YdAUnAO|Ac#`IyEvz#eAvQ"
I am passing this value from c# into a razor view. if there is anyway to set it in the hidden field using javascript without losing any info that will be good.
In JavaScript strings are surrounded by quotes. you can have quotes in the middle of a string, but you have to escape them with a "\". You might need to escape special characters. if your string has combinations of single quotes and double quotes then escaping those characters should help you.
sample escaping double quotes:
var token = "asdasd\"asdasd";
looks like your sample string does not throw error. see code in link:
http://codepen.io/anon/pen/JYKpEP
Related
If I want to find a reference to precisely the following string:
http ://www.mydomain.com/home
within a more complex regex expression.
Is it possible to escape the whole sequence instead of escaping each / and . character individually? To get something more readable than
/http:\/\/www\.mydomain\.com\/home/
In the regex parsing site https://regexr.com/ , if I type the url in and set a regex to
/(http ://www.mydomain.com/home)/
, it appears to recognize the string, yet declares an error:
Unescaped forward slash. This may cause issues if copying/pasting this expression into code.
So I'm confused about this issue.
It appears that regex does not offer such a syntax, at least for Javascript. It is possible, however, to proceed as follows:
use a string and automatically escape all the special characters in it,
as indicated here: Javascript regular expression - string to RegEx object
concatenate that string with strings representing the rest of the expression you want to create
transform the string into a regex expression as indicated in Escape string for use in Javascript regex .
With JSON.parse:
This works:
JSON.parse('{\"V\":\"\u008c\"}') // => { V: '' }
This doesn't:
JSON.parse('{\"V\":\"\u0000\"}') // >> SyntaxError: Unexpected token in JSON at position 6
What is the concept here?
You can find some information in the RFC 4627. For example:
2.5. Strings
The representation of strings is similar to conventions used in the C
family of programming languages. A string begins and ends with
quotation marks. All Unicode characters may be placed within the
quotation marks except for the characters that must be escaped:
quotation mark, reverse solidus, and the control characters (U+0000
through U+001F).
Now, related to your problem, you just need to escape the \ on your unicode character for the parsing to work:
JSON.parse('{"V":"\\u0000"}')
Result: {V: "�"}
And just for you information, no need to escape the " inside a single-quoted string in javascript.
The only issue is that you're expressing your JSON as a Javascript string literal. This is valid JSON:
{"V":"\u0000"}
This however is a Javascript string containing the value {"V":"<NUL>"}:
'{\"V\":\"\u0000\"}'
Javascript was already interpreting the \u0000 escape sequence and JSON.parse was consequently trying to parse a JSON string with a NUL byte in it, which is illegal (NUL must be escaped).
The actual Javascript string literal representation of the JSON you were attempting is:
JSON.parse('{"V":"\\u0000"}')
↑
Humour me on this one.
In my code I am attempting to find all the divs that match a data-attribute value. Now this value is created by a user so the string could contain anything.
During my testing I ran into an error when the value contained a quote and ended with a backslash "\" (The javascript escape character).
Error: Syntax error, unrecognized expression:
className[data-attributename="Mac"Mac\"]
Here is an example (please note in this example the double backslash escapes itself and the first backslash escapes the quote):
var value= "Mac\"Mac\\";
$('.className[data-attributename="'+value+'"]');
This error only occurs if the string contains a quote (") and has a backslash (\) at the end of the string. If there is a space after the backslash or if the backslash is in beginning or middle of the string there is no issue.
Is it possible to pass a variable that includes a quote or apostrophe ( " ' ) and ends with a backslash (\) into the jQuery Attribute Equals Selector?
One obvious solution would be just to prevent my users from using the backslash "\" character. If I do this is there any other characters that could be harmful using this jQuery selector?
Another solution would be:
var value= "Mac\"Mac\\";
$('.className').each(function(){
if($(this).attr('data-attributename') === value){
//perform action
}
});
With this solution would it be less efficient because it would have to iterate through each element or does the Attribute Equals Selector essentially work the same way? If so, for safety should I always use this solution over the attribute equals selector?
Here is an example of the div I would be trying to select:
$('body').append("<div class='className' data-attributename='Mac\"Mac\\' ></div>")
You will have to use the second solution to get jQuery working.
Similar questions have been asked an this is an answer to one of them. jQuery selector value escaping
$("#SomeDropdown >option[value='a\\'b]<p>']")
But this doesn't work in
jQuery because its selector parser is not completely
standards-compliant. It uses this regex to parse the value part of an
[attr=value] condition:
(['"]*)(.*?)\3|)\s*\]
\3 being the group containing the opening
quotes, which weirdly are allowed to be multiple opening quotes, or no
opening quotes at all. The .*? then can parse any character, including
quotes until it hits the first ‘]’ character, ending the match. There
is no provision for backslash-escaping CSS special characters, so you
can't match an arbitrary string value in jQuery.
You can use escape() function to escape the special character like
value = escape('Max\\'); //it will return Max%5C
When JSON string has \ at the end of any string it gives me:
Ext.JSON.decode(): You're trying to decode an invalid JSON String
JSON decode error:
Uncaught Ext.JSON.decode(): You're trying to decode an invalid JSON
String:
[{"ID1":"1","ID2":"1","NAME":"Act\"},{"ID1":"3","ID2":"1","NAME":"Act\"},{"ID1":"4","ID2":"2","NAME":"act $#%^&&*"},{"ID1":"2","ID2":"2","NAME":"act $#%^&&*"}]
How can i avoid above error?
That is invalid JSON, because the \ character escapes the " mark which would be responsible for closing the string - as such, your string remains unclosed (that is, until the next " comes around).
So your problem is that a backslash has a special meaning inside strings. If you want to use slashes, use \\ instead. (Note that what this does is escape the backslash character itself.)
ie.:
{"ID1":"1","ID2":"1","NAME":"Act\\"}
You need to escape that backslash. Initially I thought you would only need to use one escape character, but, according to this demonstration, you need to use three:
{"ID1":"1","ID2":"1","NAME":"Act\\\\"}
If you test your JSON, you will see that it's not valid : http://jsonlint.com/
You'll need to escape your \ with another \
\\Act
You should encode your JSON before, or make it manually if possible.
I am of the understanding that if I am trying to stringify quotes (' and "), i need to escape them but I can't explain the following results when I tried the same out in firebug:
1. >> JSON.stringify({foo: "a"a'a"});
SyntaxError: missing } after property list
Inference: This is expected since I didn't escape " and '
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
Inference/Question: Will the JSON string also show the escape character before " and why it works without escaping the single quote
Also JSON throws an error when I try to parse the output string generated above back to JS object ?
>>> JSON.parse("{"foo":"a\"a'a"}")
SyntaxError: missing ) after argument list
Finally Explain results below: Basically if I escape the single quote once, it doesn't show up in the output string but if I escape twice, it does
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
Basically I am trying to understand when and how I need to escape single and double quotes when converting to and from JSON.
Thanks for your help
EDIT:
Thanks for the replies .
The first 2 queries are clear. So I only need to escape the quotes I am using to enclose the string ( in my case ") and escape any escape characters itself in the string. Other than these 2, I don't need to escape any other chars?
I am not clear on the last query. If I just increase the escape characters before ', why does it shows even number of escape chars in the output . For eg
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
>>> JSON.stringify({foo: "a\"a\\\'a"});
"{"foo":"a\"a\\'a"}"
The format given by your JavaScript interpreter here is a little misleading when it outputs the following:
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
The interpreter is adding the double quotes on the outside without doing any of the necessary escaping to make the result a valid string literal, so what this is actually trying to say is that the result of the expression is a string that contains {"foo":"a\"a'a"} (where every character there is literal, including the backslash). If you were going to write this as a JavaScript string literal it would be one of the following:
With double quotes: "{\"foo\":\"a\\\"a'a\"}"
With single quotes: '{"foo":"a\\"a\'a"}'
The above strings are exactly identical, they are just represented differently based on which external quote is used. You should be able to pass either of those strings to JSON.parse and get an object equivalent to what you started with.
Hopefully this will also help to clarify as to why the single quote isn't escaped, as shown above you only need to escape the type of quote that is used for the string literal (so escape internal double quotes if double quotes surround the string, and escape internal single quotes when single quotes are around the string).
So the errors being thrown is because the string is being ended. So any other characters that follow are attempted to be parsed but aren't able to be. Hence the errors.
So because you start with a quotation mark ("), using an apostrophe (') isn't ending the string. It's within the string, because your string is expected to end with another quotation mark.
If you want to include the same character that the string is defined within, it will need to be escaped. E.g. " and he said \"what a great day!\" to the other boy"
No need to escape single quotes inside of double quotes, or double quotes inside of single quotes.
You do need to escape like quotes within like quotes -- these are all valid syntax:
var a = "Testing '1234'";
var b = 'Testing "1234"';
var c = "Testing \"1234\"";
var d = 'Testing \'1234\'';
Second piece, on JSON stringification, the double quotes you see output here:
JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
are just an output within whatever console or repl you are using. Technically those should be output as single quotes.
At any rate...
var s = JSON.stringify({foo: "a\"a'a"});
JSON.parse(s);
...will most definitely output a valid object.
Your first inference is correct; you need to escape any special characters (Quotation marks, in this case) that you want to appear in your final string. If you don't, then the browser will try to parse the string as-is, and will fail miserably because of mismatched quotes.
This is the same reason you get an error when you're parsing the string; the parser can't account for the mismatched quotes.
For the last behaviour you were having trouble with, you're not really escaping the quote twice; you're escaping the escape character.