0

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"
           controller="SampleClass">

     <!--rest of the code-->

     <script type="text/javascript">

          /**code**/

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

    </script>

</apex:page>

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?

2
  • 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 '20 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 '20 at 15:50
1

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

1
  • thnks.. it worked May 7 '20 at 15:53
2

If you wanted the actual string:

let sampleString = "{!JSENCODE(sampleString)}";
console.log(sampleString.length);

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

1
  • the other answer worked for me.. anyway thnks for helping. May 7 '20 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.