Accesing values with quotes in javascript or jquery - JSENCODE

JavaScript is a light weight client side scripting language will make your Salesforce page (Visualforce page ) do some small tasks in client side browser itself.

You can simply assign you apex public variable directly to your JavaScript variable and perform JavaScript actions like the following code snippet

var accountName = '{!someAccount.Name}';

//someAccountis a public get set variable in your apex class associated with this VF page

But when the account name has single quotes (') in it for example : example's name.

This will break the above code and throws JavaScript error as shown in below screenshots.

The above screenshots the JavaScript error message in browser console which can be opened by (Right click on the page -> Inspect element  -> choose Console tab).

Double click on the error message it will show us in which line the error occurred as shown below.

The single quotes has broke our assignment code.

In order to overcome this issue we want to use the JSENCODE JavaScript method. Which inserts backslash (\) before the single quotes.

The following is the description given in the Salesforce documentation.

Function :


​Description :

Encodes text and merge field values for use in JavaScript by inserting escape characters, such as a backslash (\), before unsafe JavaScript characters, such as the apostrophe (').

Use : 

{!JSENCODE(text)} and replace text with the merge field or text string that contains the unsafe JavaScript characters.


After inserting the JSENCODE method the output is rendered as the following screenshot.

var accountName = '{!JSENCODE(someAccount.Name)}';

Note :
JSENCODE  only accepts text input if you are using any other input format you want to  convert it to text and then pass it to the JSENCODE method.

This concludes this post. Let me know your thoughts in comments.

Happy coding !!!smiley

No votes yet