TransWikia.com

How to truncate a string to a specific length if it is longer?

Salesforce Asked by imajmdf on February 10, 2021

How can I make it that I can reduce the length of a String? Like for example the string.Length() = 300.

My goal is to make it to 120 characters, retaining the left side (e.g. NameOfThePerson to NameofThePers).

string sizeString = 'Imagine this is more than 120 Characters';
if(sizeString.Length() > 120){
    //insert logic here to make it 120 characters
}

4 Answers

Another way to do this, especially addressing the specific question,

My goal is to make it to 120 characters, retaining the left side

Use the left(length) method from the String class

and here's a usage example:

String s1 = 'abcdaacd';
String s2 = 
s1.left(3);
System.assertEquals('abc', s2);

and for your example would be,

string sizeString = 'Imagine this is more than 120 Characters';
string resizedString = '';
if(sizeString.Length() > 120){
    resizedString = sizeString.left(120);
}

Answered by Bahman.A on February 10, 2021

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')

Answered by Kimball Robinson on February 10, 2021

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());

Answered by Keith C on February 10, 2021

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);
}

Answered by Oleksandr Berehovskyi on February 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP