How to truncate a string to a specific length if it is longer?
As an indicator to the user that the string has been shortened, also adding '...' to the end can be helpful.
There is a String method that does that:
String newString = sizeString.abbreviate(120);
This example from the help illustrates how the length of the '...' is also considered:
String s = 'Hello Maximillian';
String s2 = s.abbreviate(8);
System.assertEquals('Hello...', s2);
System.assertEquals(8, s2.length());
Use substring method of String
class
Returns a new String that begins with the character at the specified zero-based startIndex and extends to the character at endIndex - 1.
String sizeString = 'Let\'s Imagine this is more than 120 Characters';
Integer maxSize = 120;
if(sizeString.length() > maxSize ){
sizeString = sizeString.substring(0, maxSize);
}
If you don't want an ellipsis character, use a quick regular expression to match only the first 80 (or whatever number) characters, and replace the string with just those.
yourString.replaceFirst('^(.{80}).*', '$1')