Loading

Considerations for Using the Apex String Class substring Method with Surrogate Pairs in Salesforce

Udgivelsesdato: Mar 24, 2026
Beskrivelse

In Apex, surrogate pair characters are interpreted as a single character by combining a "high surrogate" and a "low surrogate". Therefore, if you use the substring(0, 1)` method on a String variable containing a single surrogate pair to extract only the high surrogate, Apex does not interpret the result as a valid surrogate pair, and the character cannot be retrieved correctly.

Løsning

This article explains why the Apex String class substring method returns an invalid character when you extract a surrogate pair character, and how to retrieve the full character. This happens because the Apex substring method counts each surrogate (high and low) as a separate index position, even though they represent one visible character. To correctly retrieve a surrogate pair character, your code must grab both positions together.

Example of the Problem

Suppose a String variable `myStr` contains a single surrogate pair character (for example, certain emoji or rare CJK characters use surrogate pairs). The following Apex code calls substring with an end index of 1:

String result = myStr.substring(0, 1);

This code returns only the high surrogate half of the character, which is not valid on its own and does not display or compare correctly.

Corrected Code

To retrieve the full character, include both the high and low surrogate by using an end index of 2 instead of 1. The following Apex code returns both surrogate values together:

String result = myStr.substring(0, 2);

This retrieves both surrogate values together, so the character is extracted correctly.

Vidensartikelnummer

000395737

 
Indlæser
Salesforce Help | Article