Escaping javascript variable double quotes - javascript

I'm using Ajax calls to get some variables data from the DB.
some of my data stored on the database contains double quotes (").
when I'm trying to display the variable :
value="'+ucontent+'"
the string gets cut in the middle (of course)
I have tried using escape() but im getting a non readable result - something with %4%2 etc...
how can i escape the double quotes in the variable and still keep a readable string...
BTW - I'm using UTF8 characters.

decodeURIComponent()
might be helpful
what escape actually does is replace some characters with a hexadecimal escape sequence.
That is the reason why you are getting unreadable string like %4%2.

Depends on what language in server side you are using.
If it is php, then use json_encode to encode the response string.
If it is ruby(rails), then use escape_javascript to escape the response string.

You can just use \" if you don't use an encoder. See this.

Related

JSON.parse failing on valid Json. Have escaped control characters.If

I've escaped control characters and am feeding my validated JSON into JSON.parse and jQuery.parseJSON. Both are giving the same result.
Getting error message "Unexpected token $":
$(function(){
try{
$.parseJSON('"\\\\\"$\\\\\"#,##0"');
} catch (exception) {
alert(exception.message);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Thanks for checking out this issue.
What's happening here is that there are two levels of backslash removal being applied to the string. The first is done by the browser's JavaScript engine when it parses the single-quoted string. In JavaScript, single-quoted strings and double-quoted strings are exactly equivalent (other than the fact that single-quotes must be backslash-escaped in single-quoted strings and double-quotes must be backslash-escaped in double-quoted strings); both types of strings take backslash escape codes such as \\ for backslash, \' for single-quote (redundant but accepted in double-quoted strings), and \" for double-quote (redundant but accepted in single-quoted strings).
In your JavaScript single-quoted string literal you have several instances of this kind of thing, which are meant to be valid JSON double-quoted strings:
"\\\\\"$\\\\\"#,##0"
After the browser has parsed it, the string contains exactly the following characters (including the outer double-quotes, which are unremoved because they are contained in a single-quoted string):
"\\"$\\"#,##0"
You can see that each consecutive pair of backslashes became a single literal backslash, and the two cases of an odd backslash followed by a double-quote each became a literal double-quote.
That is the text that is being passed as an argument to $.parseJSON, which is when the second level of backslash removal occurs. During JSON parsing of the above text, the leading double-quote signifies the start of a JSON string literal, then the pair of backslashes is interpreted as a single literal backslash, and then the immediately following double-quote terminates the JSON string literal. The stuff that follows (dollar, backslash, backslash, etc.) is invalid JSON syntax.
The problem is that you've embedded valid JSON in a JavaScript single-quoted string literal, which, although it happens to be valid JavaScript syntax by fluke (it wouldn't have been if the JSON contained single-quotes, or if you'd tried using double-quotes to delimit the JavaScript string literal), no longer contains valid JSON after being parsed by the browser's JavaScript engine.
To solve the problem, you have to either manually escape the JSON content to be properly embedded in a JavaScript string literal, or load it independently of the JavaScript source, e.g. from a flat file.
Here's a demonstration of how to solve the problem using your latest example code:
$(function() {
try {
alert($.parseJSON('{"key":"\\\\\\\\\\"$\\\\\\\\\\"#,##0"}').key); // works
alert($.parseJSON('{"key":"\\\\\"$\\\\\"#,##0"}').key); // doesn't work
} catch (exception) {
alert(exception.message);
}
});
http://jsfiddle.net/814uw638/2/
Since JavaScript has a simple escaping scheme (e.g. see http://blogs.learnnowonline.com/2012/07/19/escape-sequences-in-string-literals-using-javascript/), it's actually pretty easy to solve this problem in the general case. You just have to decide in advance how you're going to quote the string in JavaScript (single-quotes are a good idea, because strings in JSON are always double-quoted), and then when you prepare the JavaScript source, just add a backslash before every single-quote and every backslash in the embedded JSON. That should guarantee it will be perfectly valid, regardless of the exact JSON content (provided, of course, that it is valid JSON to begin with).
In your original problem, why do you need to do JSONparse in the first place? You could have easily gotten the object you wanted by just doing
var o = { blah }
by manually removing the single quotes you have around the curly braces rather than doing
$.JSONparse('{blah}')
Is there any reason for evaluating the string first (ie var s = '{blah}' and then doing $.JSONparse(s)) which is what your original code was doing? There shouldn't be a case where this is necessary. Since you mentioned somewhere that the string was produced by JSON.stringify, there shouldn't be a scenario where you need to explicitly store it into a variable (ie copy and paste it and put quotes around it).
The main problem here is the string produced by JSON.stringify, which is properly escaped, has been 'evaluated' once when you manually put braces around it. So the key is to make sure the string doesn't get 'evaluated'
Even if you wanted to pass the stringified variable to database or anything, there is no need to explicitly use quotes. One could do
var s = JSON.stringify(obj);
db.save("myobj",s)
var newObj = JSON.parse(db.load("myobj"))
The string is stored verbatim without getting evaluated, so that when you retrieve it, you would have the exact same string.

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

Error using Javascript and JSP, string with space gives `Unterminated string literal`

I have to pass a string value to JavaScript from JSP page.
I am using
display("<%=name%>")
It works fine but when i have string like 'sweet milk', JavaScript throws the error
Unterminated string literal
How to solve this?
Your string contains single quotes - you can escape single quotes as "\x27" and double quotes as "\x22" and then pass it to javascript.
You probably have characters in your String that should be escaped in Javascript. For example, if your string is My name is "John", your code will generate
var a = "My name is "John"";
which is invalid.
You should use StringEscapeUtils.escapeJavaScript from commons-lang to make sure everything is correctly escaped (single and double quotes, newlines, tabs, etc.).
I guess there's an error in the generated JavaScript code. Is there any way to look at you page? I suggest to look at the generated source code of that page.

javascript escape problem with unicode characters

I use the following jquery code to load some date on a specific event from external file:
$("#container").load("/include/data.php?name=" + escape(name));
if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1
How can I deal with this encoded symbols? I need to convert them back to readable one.
When I remove the escape function and leave just "name" variable the code doesn't work any more...
Can anyone please help?
If you want to do this manually, then you should be using encodeURIComponent, not escape (which is deprecated)
The jQuery way, however, would be:
$("#container").load("/include/data.php", { "name": name });
Either way PHP should decode it automatically when it populates $_GET.
This may help you.
javascript - how to convert unicode string to ascii

JSON.parse string with quotes

I have this:
JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5\" SATA2 7200rpm"}}');
JSONLint says it's perfectly valid json. But on execution I have a JSON.parse error.
But, if I change my code to:
JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5\\" SATA2 7200rpm"}}');
(note the double backslash)
It works, but now JSONLint says invalid json.
Can someone help to understand this behavior?
It's a difference between the wire format, and what you have to write in your code to get the wire format. When you declare this in code you need the double-\ in your literal so the string gets a single backslash (otherwise it will interpret \" as an escape sequence for just declaring a " and put that in your string). If you print out the value of the literal you will see a single backslash.

Categories

Resources