JavaScript - Escape single quote in the JavaScript Object property value

c#, javascript, jquery, json

Solution

The first line of code you show is not valid JavaScript:

var fileUploadDic = { 'firstname': 'Jo''hn', 'lastname' : 'Macy' , 'country' : 'USA };

Because the string `'Jo''hn'` can't have single quotes in it like that. It needs to be either `'Jo\'hn'` or `"Jo'hn"`. That is to say that if your JS string is quoted with single quotes you have to escape each single quote character within the string with a backslash, but if your JS string is quoted with double quotes you can use singles freely within the string. If you want two single quotes in a row `'Jo\'\'hn'` or `"Jo''hn"`.

There is nothing you can do to fix this client-side, because being invalid JavaScript it won't run.

You have to fix it server-side; the easiest way is probably to escape it with a backslash, noting that if that is in a C# string you'll need to escape the backslash too so that the actual output to the browser contains a backslash:

"var fileUploadDic = { 'firstname': 'Jo\\'hn', 'lastname' : 'Macy' , 'country' : 'USA };"

Problem

In my case, I am trying to split the JavaScript Object dynamically into the HTML markup from C#.NET code behind. After getting the data, I prepare the string and create the object in the string and then spit it to the HTML markup. ``` var fileUploadDic = { 'firstname': 'Jo''hn', 'lastname' : 'Macy' , 'country' : 'USA }; ``` Later on in some other action, such as button click, I tried to pull the firstname, and it gives me a JavaScript error because the value in the firstname property is not escaped to handle the single quote. Although I can do it while preparing the object string in the code backend, I like to do something at the client side instead. ``` var dv = $('#dv1') dv.append(fileUploadDic.firstname); //gives me error. dv.append(fileUploadDic.lastname); dv.append(fileUploadDic.country); ``` Is there any way in the JavaScript, that I can do the character escaping while fetching it from the object. http://jsfiddle.net/uagFu/8/

Original source