Escape apostrophe in a string saved in a cookie - javascript

I need to save a string value in a cookie, and that string (a person's last name) may contain an apostrophe, like O'Bama.
I tried lastName.replace(/'/, "\'").toString(); but I get undefined in a cookie.
What am I doing wrong, and how should this be done correctly?

Use the escape() function in javascript:
lastname = escape(lastname);
To undo this operation just call unescape()...
This will encode all special chars to store them in your cookie.
Some reference: http://www.w3schools.com/jsref/jsref_escape.asp

you only need to escape the string using javascript function:
escape()
and unescape to get the actual value
unescape()

Related

Unexpected token % in angularjs

Code:
$scope.username=JSON.parse(getCookie('authData')).Username;
This is what getCookie('authData') contains:
%7B%22UserID%22%3A%22c980b08240178f48a4607cd1d081664b%22%2C%22Username%22%3A%22sajeetharan%40duosoftware.com%22%2C%22Name%22%3A%22sajeetharan+sinnathurai%22%2C%22Email%22%3A%22sajeetharan%40duosoftware.com%22%2C%22SecurityToken%22%3A%22a7dd024d5158c7e1ee4807cb9716cc6f%22%2C%22Domain%22%3A%22sajeetharan.digin.io%22%2C%22DataCaps%22%3A%22%22%2C%22ClientIP%22%3A%22104.155.236.85%3A33776%22%2C%22Otherdata%22%3A%7B%22JWT%22%3A%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkbW4iOiJzYWplZXRoYXJhbi5kaWdpbi5pbyIsImVtbCI6InNhamVldGhhcmFuQGR1b3NvZnR3YXJlLmNvbSIsImlzcyI6InNhamVldGhhcmFuLmRpZ2luLmlvIiwic2NvcGUiOnt9LCJzdCI6ImE3ZGQwMjRkNTE1OGM3ZTFlZTQ4MDdjYjk3MTZjYzZmIiwidWlkIjoiYzk4MGIwODI0MDE3OGY0OGE0NjA3Y2QxZDA4MTY2NGIifQ%3D%3D.YpFKYAw0t3RQkbrM9sjY1QAkz4AUxsmlE5uXMy%5C%2Fsc%3D%22%2C%22Scope%22%3A%22%22%7D%7D
What could be the issue?
Try the function decodeURIComponent():
$scope.username=JSON.parse(
decodeURIComponent(getCookie('authData'))
).Username
The cookie value is just encoded.
Cookie values may not include semicolons, commas, or whitespace. For
this reason, you may want to use the JavaScript encodeURIComponent()
function to encode the value before storing it in the cookie. If you
do this, you will also have to use the corresponding
decodeURIComponent() function when you read the cookie value.
More details in this tutorial.

Passing a string value from c# file to js file

I am trying to pass a string value from c# file to js file.
If I try to pass an int value, then I can pass it, but I am unable to pass string value.
string value = "abc";
int a=5;
TableCell.Attributes.Add("onclick", "F1("+value +")"); //NOTHING HAPPENS
TableCell.Attributes.Add("onclick", "F1("+a +")"); //Works Perfectly
js file
function F1(value) {
alert(value);
}
Pass string value in quotes ''
Use
TableCell.Attributes.Add("onclick", "F1('"+value +"')");
^ ^
Otherwise it treated as variable. Currently you must be getting error in browser console.
Consider what your HTML will look like.
First version:
onclick="F1(abc)"
Second version:
onclick="F1(5)"
Clearly the second version is passing the value 5. The first version is passing the value of abc - whatever that is, within the context of the Javascript you're executing.
You could quote the string, making sure that you escape quotes etc - I'm assuming that in reality, your value is fetched dynamically from somewhere, and you might not have much control over the content. Hopefully there's something within whatever ASP.NET version you're using that will let you do that, such as HttpUtility.JavaScriptStringEncode.
For example, to get the string abc in your call, you want the attribute to be:
onclick="F1('abc')"
but if to get the string I don't know in your call, you want the attribute to be:
onclick="F1('I don\'t know')"
The key is to look at the generated HTML - pretend you're the browser, and look at the world from its perspective. Once you've worked out what HTML you want to generate, writing the code to do so is often relatively simple.
Try adding single-quotes around the value when building it in your C# string. In your first scenario, the Js is receiving:
F1(abc);
Which it reads as being the variable abc. Try adding single quotes (and it's probably best to use string.format, BTW):
TableCell.Attributes.Add("onclick", string.Format("F1('{0}')", value));
When you use the string, it would produce the JavaScript code F1(abc). That would interpret abc as a variable name, not a string literal.
Add apostrophes around the string to make it a string literal:
TableCell.Attributes.Add("onclick", "F1('" + value + "')");
If the string can contain apostrophes or backslashes, you would need to escape them:
TableCell.Attributes.Add("onclick", "F1('" + value.Replace("\\", "\\\\").Replace("'", "\\'") + "')");
This will take care of escaping any special characters (i.e. quotes, etc...)
TableCell.Attributes.Add("onclick", "F1('"+HttpUtility.JavaScriptStringEncode(value)+"')");
If you're passing a string through the argument, you need either " or ' characters to delimit it. Your variable name is translating to (adb) in the call. ("adb") or ('adb') would be the string value.
That's because it will print
F1(abc)
So it will look for a variable called abc.
You should use
TableCell.Attributes.Add("onclick", "F1(\""+value +"\")");
So the output will be
F1("abc")

How to remove escape characters from Json string?

I have a c# method that calls another method which returns back a string that is supposed to represent JSON. However, the string has escape characters in it:
public string GetPerson()
{
string person = repo.GetPerson(); //person is "{\"name\":jack,\"age\":\"54\"...
return person;
}
If I try to do a replace, there is no change:
string person = repo.GetPerson().Replace(#"\""", ""); //person still has escape characters
When I try to view person in the text viewer when debugging, the escape characters are not there--Visual Studio rips them off. But my javascript that calls this method does see the escape characters in the ajax response.
If I try to deserialize the person string into my C# User object, it does not deserialize properly:
User user = JsonConvert.DeserializeObject<User>(person);
What are my options? How can I either strip off the escape characters from the person string, or deserialize it correctly to the User object?
If a Console.WriteLine(person) shows those backslashes and quotes around the string (not just the string and quotes inside), then there is a double serialization issue. You could try first to deserialize it to a string, then to a type, like this:
User user = JsonConvert.DeserializeObject<User>(JsonConvert.DeserializeObject<String>(person));
Also, you could try to do:
string person = repo.GetPerson().Replace(#"\""", #"""");
If you have control over the API, check for double serialization on return. ASP does a default serialization, so usually you don't have to return a string with the object pre-serialized.
For webapi, use Ok(object), for ASP MVC, use Json(object, requestBehaviour) methods.

Escaping javascript variable double quotes

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.

POST data issues

I have an issue with submitting post data. I have a form which have a couple of text fields in, and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string like
title=test&content=some content
which is then submitted to the server. The problem I had is when I have '&' (eg &nbsp) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content &nbsp
How do I get around this?
Thanks in advance,
Harry.
Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content &nbsp ";
var data = encodeURIComponent('title') + /* You don't actually need to encode this as it is a string that only contains safe characters, but you would if you weren't sure about the data */
'=' + encodeURIComponent(title) +
'&' + encodeURIComponent('content') +
'=' + encodeURIComponent(content);
Encode the string..when you want to encode a query string with special characters you need to use encoding. ampersand is encoded like this
title=test&content=some content %26
basically any character in a query string can be replaced by its ASCII Hex equivalent with a % as the prefix
Space = %20
A = %41
B = %42
C = %43
...
You need to encode your query to make it URL-safe. You can refer to the following links on how to do that in JS:
http://xkr.us/articles/javascript/encode-compare/
http://www.webtoolkit.info/javascript-url-decode-encode.html
You said:
...and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string...
In the section where you are building the query string you should also run the value of each input through encodeURIComponent() as David Dorward suggested.
As you do - be careful that you only assign the new value to your processed query string and NOT the form element value, otherwise your users will think their input was somehow corrupted and potentially freak out.
[EDIT]
I just re-read your question and realized something important: you're encoding an &nbsp ;character. This is probably a more complicated issue than other posters here have read into. If you want that character, and other &code; type characters to transfer over you'll need to realize that they are codes. Those characters &, n, b, s, p and ; are not themselves the same as " " which is a space character that does not break.
You'll have to add another step of encoding/decoding. You can place this step either before of after the data is sent (or "POSTed").
Before:
(Using this question's answers)
var data = formElement.value;
data = rhtmlspecialchars(data, 0);
Which is intended to replace your "special" characters like with " " so that they are then properly encoded by encodeURIComponent(data)
Or after:
(using standard PHP functions)
<?PHP
$your_field_name = htmlspecialchars_decode(urldecode($_POST['your_field_name']));
?>
This assumes that you escaped the & in your POST with %26
If you replaced it with some function other than encodeURIComponent() you'll have to find a different way to decode it in PHP.
This should solve your problem:
encodeURIComponent(name)+'='+encodeURIComponent(value)+'&'+encodeURIComponent(name2)+'='+encodeURIComponent(value2)
You need to escape each value (and name if you want to be on the safe side) before concatenating them when you're building your query.
The JavaScript global function encodeURIComponent() does the escaping.
The global function escape() (DOM) does this for you in a browser. Although people are saying it is not doing the escaping well for unicode chars. Anyway if you're only concerned about '&' then this would solve your problem.

Categories

Resources