+ Start a Discussion
V100V100 

Problems with substring

I have a text field that i want to trim and have been trying with substring:

 

 

Field_Name__c.substring(5,27);

 However i get errors

System.StringException: Ending position out of bounds: 28

 When the field is less than 32 characters. It works fine if i say (5,10) as all have at least 15 characters.

 

 

 

Any tips on how i can trim this to ignore the first 5 characters and then return no more than 27 after that.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
prageethprageeth

 

Integer i = Field_Name__c.length();
      if (i > 32) {
        i = 27;//IF you want to return 27 characters change this value to 32
      }
return Field_Name__c.subString(5, i);

 

 

All Answers

prageethprageeth

 

Integer i = Field_Name__c.length();
      if (i > 32) {
        i = 27;//IF you want to return 27 characters change this value to 32
      }
return Field_Name__c.subString(5, i);

 

 

This was selected as the best answer
V100V100

Excellent thanks, worked perfectly

Pradeep_NavatarPradeep_Navatar

You can also try using  trim() function. Sample code is given below :

 

                                                function Trim(str)

                                                {

                                                                while (str.substring(0,1) == ' ') // check for white spaces from beginning

                                                                {

                                                                                str = str.substring(1, str.length);

                                                                }

                                                                while (str.substring(str.length-1, str.length) == ' ') // check white space from end

                                                                {

                                                                                str = str.substring(0,str.length-1);

                                                                }

 

                                                                return str;

                                                }