Substring in apex

H
E
L
L
O
W
O
R
L
D
Substring:
W
O
R
L
D
The substring "WORLD" is highlighted with arrows pointing to its start and end.

The substring function is used to extract a part of a string from a string variable.

A part of a string can be extracted from a main string using the start and end indexes. The substring() is a built-in function with two variations.

  • 1. Substring with start, end indexes
  • If you know the start and end positions, the substring function can extract a part of a string. Below is an example of how to extract the invoice id from an invoice number.
    Loading...
  • 2. Substring with start index
  • If you only know the starting index, the substring function can extract all characters from that point to the end of the string.
    Loading...

Below is an example of finding a substring in apex:

Loading...

In the above example:

  • The string variable, myString has the value 'Hello World'.
  • The first substring() method extracts the characters from position 6 to 11 (‘World’). Note, the first character is at position 0.
  • The second substring() method extracts the characters from position 6 to the end of the string (‘World’).

Try It Yourself

Loading...