String Manipulation in Salesforce #1

Salesforce provide set of methods for String manipulation. This article explains usage of each function with examples.

 

  1. Truncate strings with ellipses.
    abbreviate(maxWidth) returns a trimmed version of the String, of the specified length and with ellipses (…) appended if the current String is longer than the specified length; otherwise, returns the original String without ellipses.

    'Test Text Field'.abbreviate(8); //Test ...
  2. Convert to title case (Capitalize first letter)
    capitalize() capitalize first letter of the string.

    'test text field'.abbreviate(8); //Test text field
  3. Pad with Spaces (front & back)
    center(size) pads string with spaces in front and back while keeping String in the center.

    'test'.center(10); //    test
  4. Pad with Text (front & back)
    center(size, paddingString) pads string with specified text in front and back while keeping String in the center.

    'test'.center(10,'#'); //###test###
  5. Remove leading and trailing spaces
    trim() removes leading and trailing white spaces from the string.

    '   test    '.trim(); //test
  6. Escape characters.
    escapeCsv() – columns in CSV string enclosed with double quotes.
    escapeHtml3(), escapeHtml4() – escapes html characters in String.
    escapeJava() – escapes characters in String with Java rules. Characters escaped include quotes and control characters, such as tab, backslash, and carriage return characters.
    escapeSingleQuotes(stringToEscape) – escapes single quotes in String with backslash.
    escapeUnicode() – escapes Unicode characters.
    escapeXml() – escapes Xml tags in String.
  7. Convert first letter to lowercase
    uncapitalize() returns the String with the first letter in lowercase.

    'Test tTest Test'.uncapitalize(); //test tTest Test
  8. Convert to uppercase
    toUpperCase() Converts all of the characters in the String to uppercase using the rules of the default (English US) locale.

    'Test'.<code>toUpperCase</code>(); //TEST
  9. Convert to lowercase
    toUpperCase() Converts all of the characters in the String to uppercase using the rules of the default (English US) locale.

    'TesT'.<code>toLowerCase</code>(); //test
  10. Remove HTML tags
    stripHtmlTags() Removes all html tags from the String.

Leave a Reply