Apex String Functions: Common Methods and Examples

Formulas & functions · Updated November 22, 2026

In Salesforce Apex, “string functions” usually means methods on the built-in String type. Use methods such as trim(), contains(), substring(), replace(), and String.isBlank() to inspect, clean, compare, split, or build text; Apex strings are immutable, so methods return a result rather than changing the original string.

What String methods do in Apex

Apex is Salesforce’s strongly typed programming language, and text values are represented by the String type. A String method performs an operation on text or checks a property of it. Many are called on a string value, as in contactName.trim(); some are static methods called on the type, as in String.isBlank(contactName) or String.valueOf(42).

These methods are useful throughout Apex code: in triggers, classes, integrations, Visualforce controllers, and tests. Typical tasks include normalizing a user-entered name, checking whether a field contains a keyword, extracting part of an identifier, or making a value suitable for display. They are not Salesforce formula functions: Apex uses its own method syntax and runs as program code.

Because a String is immutable, a transformation does not overwrite the starting value. Assign the returned value if you want to keep it:

String rawName = '  Ada Lovelace  ';
String name = rawName.trim();
String greeting = 'Hello, ' + name + '!';

Here, rawName still contains the original spaces, while name is Ada Lovelace. This distinction is a frequent source of bugs when a developer calls a method but ignores its return value.

Check for empty, blank, and null values

Before processing text from a record, request, or integration, decide what to do when it is missing. String.isBlank(value) is generally the most useful test for input: it returns true for a null reference, an empty string, or a string containing only whitespace. String.isEmpty(value) checks for null or an empty string, but does not treat a string of spaces as blank.

String suppliedCode = '   ';
if (String.isBlank(suppliedCode)) {
    System.debug('A code is required.');
}

Calling an instance method directly on a null variable, such as suppliedCode.trim() when suppliedCode is null, can cause a null-pointer exception. Check for null or use String.isBlank before calling methods on potentially missing input. If whitespace is meaningful in a particular field, choose the check deliberately rather than treating every blank-looking value as invalid.

Search and compare strings

Use contains() to test whether one string occurs inside another, startsWith() and endsWith() to test boundaries, and indexOf() to find a position. An unsuccessful indexOf() search returns -1, so test that result instead of assuming a match exists. Case-insensitive variants such as containsIgnoreCase(), startsWithIgnoreCase(), and equalsIgnoreCase() make the intended comparison explicit.

Apex has a comparison detail worth remembering: the == operator compares strings without regard to case, whereas the equals() method is case-sensitive. Use equalsIgnoreCase() when case should be ignored and equals() when it should matter. Naming the intended behavior in the method call can make business rules easier to review.

String submitted = 'Salesforce';
Boolean sameExactText = submitted.equals('Salesforce');
Boolean sameIgnoringCase = submitted.equalsIgnoreCase('SALESFORCE');
Boolean hasForce = submitted.contains('Force');

Both equality checks above return true, but for different reasons: the first matches exact capitalization, and the second deliberately ignores it. The final check is also true because Force appears within the submitted text with matching case. If capitalization matters in a search, choose a case-sensitive method rather than assuming all string checks behave alike.

Extract parts of a string

Use substring(startIndex, endIndex) to get text between two positions, left(length) or right(length) to take characters from an edge, and mid(startIndex, length) to take a segment beginning at a position. Apex indexes are zero-based: the first character is at position zero. The end position supplied to substring is not included in the result.

String reference = 'INV-2048';
String prefix = reference.substring(0, 3);
String number = reference.substring(4);
Integer dashPosition = reference.indexOf('-');

In this example, prefix is INV, number is 2048, and dashPosition is 3. A substring boundary outside the available range can produce a runtime exception. Validate the input’s length or the result of indexOf() before extracting text, especially when the string comes from an external system and its format is not guaranteed.

For delimiter-based text, split() returns a List<String>. For example, a comma-separated value can be split into entries and then examined individually. The delimiter argument is a regular expression, not always a literal character; characters with special regex meaning may need escaping. Use a structured format such as JSON, with an appropriate parser, instead of relying on splitting when values can themselves contain delimiters.

Clean, replace, and change case

trim() removes whitespace at the beginning and end. toLowerCase() and toUpperCase() return case-converted strings, while replace(oldText, newText) replaces literal matching text. For example, a label can be cleaned before display with String cleaned = rawLabel.trim();. These operations return new values; keep assigning the result if multiple transformations are needed.

replaceAll(regex, replacement) uses a regular expression, which makes it useful for patterns but different from a plain text replacement. For instance, replacing repeated whitespace with one space can be done with input.replaceAll('\\s+', ' ') in Apex source. Regex patterns and replacement strings have their own special characters, so test patterns with representative input. If the goal is to replace a known literal substring, prefer replace() to avoid accidentally treating punctuation as regex syntax.

Other useful methods include remove() for removing occurrences of text, substringBefore() and substringAfter() for working around a delimiter, and capitalize() for changing the first character’s case. Pick the method that expresses the intended operation; manual index arithmetic can be harder to understand and more vulnerable to malformed input.

Convert values and assemble text

String.valueOf(value) converts supported values to their string representation. It is handy when building a message that includes a number or date, but conversion is not validation: it does not prove that text is suitable for a particular field, query, or external format. Handle null explicitly when a null value needs a particular display, fallback, or error behavior.

For a small message, concatenation with + is straightforward. When joining a collection of text values with a separator, use String.join(values, separator). For example:

List<String> regions = new List<String>{'North', 'Central', 'South'};
String regionList = String.join(regions, ', ');

The result is North, Central, South. This is clearer than manually adding a comma after each item and then removing the final comma. For complicated message templates, keep formatting and null-handling rules explicit so a missing value does not accidentally produce confusing output.

Choose the right method and avoid common mistakes

Choose based on the actual requirement, not just the shortest-looking expression. A useful selection guide is:

  • To reject absent or whitespace-only input, use String.isBlank().
  • To remove surrounding whitespace, use trim() and assign its return value.
  • To test for literal text, use contains(); use an ignore-case variant only when case truly does not matter.
  • To locate a delimiter, use indexOf() and check for -1 before extracting a substring.
  • To replace plain text, use replace(); reserve replaceAll() for regular-expression patterns.
  • To combine a list of values, use String.join() instead of adding separators manually.

One common misconception is that calling a method changes the original string. It does not: raw.trim(); by itself discards the returned value. Another is that isEmpty() and isBlank() mean the same thing. They differ for whitespace-only text, which matters for form validation and imported data. A third is that substring() uses one-based positions; it uses zero-based positions, and its ending index is exclusive.

Also consider performance and limits when processing large volumes of records. Apex runs under platform governor limits, so avoid needless repeated transformations inside loops when a value can be cleaned once and reused. String concatenation is appropriate for ordinary short messages; for large or complex output, measure the real workload and structure the code to avoid repeated unnecessary work. Do not assume a method makes input safe for every destination: escaping, validation, and encoding depend on whether text is going into SOQL, HTML, a URL, or another context.

Security and handling external text

String methods can help with safe handling, but no single method makes untrusted input universally safe. For dynamic SOQL, prefer bind variables rather than building a query by concatenating user input. String.escapeSingleQuotes() can escape quote characters in specific dynamic-query situations, but it is not a substitute for bind variables and does not protect other parts of a query, such as object names or field names. Those identifiers should be controlled or allow-listed.

Likewise, trimming or replacing characters is not HTML encoding. If text is rendered into HTML, use the appropriate output-encoding mechanism for that context. For inbound data, validate that it meets the expected format and length before using it. These practices reduce injection and formatting errors while preserving legitimate text that should not be discarded.

Frequently Asked Questions

What is the difference between String.isEmpty() and String.isBlank() in Apex?
isEmpty() checks for null or an empty string, while isBlank() also treats whitespace-only text as blank. For most required user-entered text, String.isBlank() is the more inclusive check.

Are Apex string comparisons case-sensitive?
The == operator compares strings case-insensitively in Apex. The equals() method is case-sensitive; use equalsIgnoreCase() when you want an explicit case-insensitive comparison.

How do I get part of a string in Apex?
Use methods such as substring(), left(), right(), or mid(). Indexes start at zero, and substring(start, end) does not include the end index. Check boundaries before extracting from variable input.

Does trim() modify the original Apex string?
No. Strings are immutable, and trim() returns a new string. Assign the result, for example value = value.trim();, if you want to retain the cleaned text.

Should I use replace() or replaceAll()?
Use replace() for literal text. Use replaceAll() when the search is a regular-expression pattern, and account for regex escaping and special characters.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.