I have a visualforce page and an apex controller class. There is a string variable inside the apex class and i want to find the length of that string from visualforce page using javascript.

global with sharing class SampleClass{
     public String sampleString{get; set;}

     /***rest of the code**/

<apex:page showHeader="false"

     <!--rest of the code-->

     <script type="text/javascript">


         console.log('LENGTH: ' + ({!sampleString}).length);



When I run the above code, this: LENGTH: undefined is what i am getting. And I have already checked whether there is value inside the string. sampleString is not null and it has value inside it. So, what am i doing wrong? Is there any other way to do it?

  • 1
    Is there a reason why you need to do this in Javascript? If sampleString is set in your controller, you could just system.debug(sampleString.length()); That aside, the Javascript property you're looking for is length, not size
    – Derek F
    May 7, 2020 at 15:47
  • ya i meant length. I just checked if size was working and forget to change it back before copying the code. And also yes, I have to check it in javascript. May 7, 2020 at 15:50

2 Answers 2


I believe you can use {!LEN(sampleString)}

  • thnks.. it worked May 7, 2020 at 15:53

If you wanted the actual string:

let sampleString = "{!JSENCODE(sampleString)}";

You need to make sure you put the string in quotes, and also use JSENCODE to make sure it doesn't get encoded incorrectly.

  • the other answer worked for me.. anyway thnks for helping. May 7, 2020 at 15:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .