Salesforce Apex provides a rich set of built-in String methods for manipulating text, including substring(), contains(), split(), replaceAll(), and many more. These functions are part of the Apex String class and are essential for parsing, formatting, and validating data in triggers, classes, and flows.
Why String Functions Matter in Apex
In Salesforce development, you constantly work with text: record names, email addresses, JSON payloads, CSV imports, and custom labels. String functions let you extract, compare, and transform that text without writing complex loops or external libraries. They are the building blocks for data cleaning, dynamic SOQL, and user-facing messages. For example, you might use String.isBlank() to validate required fields or String.escapeSingleQuotes() to safely include user input in dynamic SOQL queries.
Core String Methods You’ll Use Daily
The Apex String class includes dozens of methods. Here are the most frequently used ones, grouped by purpose:
- Checking content:
contains(),containsIgnoreCase(),startsWith(),endsWith(),isBlank(),isNotEmpty(),isNumeric() - Extracting parts:
substring(),substringAfter(),substringBefore(),left(),right(),mid() - Transforming:
toLowerCase(),toUpperCase(),normalizeSpace(),trim(),replace(),replaceAll(),replaceFirst() - Splitting and joining:
split(),join()(on a list),split('\\n')for lines - Formatting and conversion:
format(),valueOf(),escapeHtml4(),escapeSingleQuotes(),unescapeHtml4()
Each method returns a new String (strings are immutable in Apex) or a Boolean/Integer, so you can chain calls like myString.trim().toLowerCase().
How to Use Them: Syntax and Examples
String methods are called on a string instance or the String class itself. Here are concrete examples you can run in an anonymous Apex window:
String name = ' Salesforce Developer ';
System.debug(name.trim()); // 'Salesforce Developer'
String email = 'user@example.com';
System.debug(email.substringBefore('@')); // 'user'
System.debug(email.substringAfter('@')); // 'example.com'
String csv = 'red,green,blue';
List<String> colors = csv.split(',');
System.debug(colors.size()); // 3
String phrase = 'The quick brown fox';
System.debug(phrase.replace('quick', 'slow')); // 'The slow brown fox'
System.debug(phrase.replaceAll('\\s+', '-')); // 'The-quick-brown-fox'
Note that split() takes a regular expression, so special characters like . or | must be escaped. For example, 'a.b'.split('\\.') returns ['a','b'].
Choosing the Right Function
With many overlapping methods, picking the right one can be tricky. Here’s a quick decision guide:
- Need to check if a string contains a substring? Use
contains()orcontainsIgnoreCase()(case-insensitive). - Need to extract text before or after a delimiter? Use
substringBefore()orsubstringAfter()—they return the whole string if the delimiter isn’t found, unlikesubstring()which throws an exception. - Need to replace all occurrences of a pattern? Use
replaceAll()with a regex; for literal replacement, usereplace(). - Need to split on a literal comma? Use
split(','); for a comma with optional spaces, usesplit('\\s*,\\s*'). - Need to check if a string is null or empty? Use
String.isBlank()(covers whitespace) rather than== ''.
Remember that substring() uses zero-based indexing and throws System.StringException if the indexes are out of bounds. Always validate length before calling it.
Common Pitfalls and How to Avoid Them
Developers often trip over a few quirks:
- Null handling: Calling a method on a null string throws a NullPointerException. Use
String.isBlank()or safe navigation likemyString?.contains('x')(Apex supports safe navigation in recent versions). - Regex escaping: In
split()andreplaceAll(), backslashes must be doubled. For example, to split on a period, usesplit('\\.'). - Case sensitivity:
contains()is case-sensitive. UsecontainsIgnoreCase()or convert to lower case first. - Whitespace:
trim()only removes leading/trailing spaces, not all whitespace. UsenormalizeSpace()to collapse internal multiple spaces. - Unicode and special characters: Some methods like
length()count UTF-16 code units, so emojis may count as two. UsecodePointCount()if needed.
One common misconception is that String.isEmpty() checks for whitespace—it doesn’t. isEmpty() only returns true for a zero-length string, while isBlank() also returns true for strings containing only spaces.
Performance and Best Practices
String manipulation in Apex is generally fast, but be mindful in loops over large collections. Each method call creates a new string, so avoid unnecessary chaining in a loop. Instead, build strings using StringBuilder (via String.join() or concatenation with += is fine for small sizes). For bulk operations, consider using String.join() on a list rather than repeated concatenation.
Also, when using dynamic SOQL, always use String.escapeSingleQuotes() on user input to prevent SOQL injection. For example:
String searchTerm = 'O\'Brien';
String query = 'SELECT Id FROM Account WHERE Name = \'' + String.escapeSingleQuotes(searchTerm) + '\'';
List<Account> accs = Database.query(query);
Alternatives to String Methods
While String methods cover most needs, sometimes you need more power:
- Regular expressions: Use the
PatternandMatcherclasses for complex pattern matching and extraction. - JSON serialization: For structured data, use
JSON.serialize()andJSON.deserialize()instead of manual string parsing. - Formula fields: For simple transformations in reports or record pages, consider using formula functions like
LEFT()orREGEX()instead of Apex. - Flow formulas: In Flow, you can use similar text functions in formulas without writing code.
Frequently Asked Questions
How do I split a string by newline in Apex?
Use myString.split('\\n') to split on line breaks. If your data uses \r\n (Windows), use split('\\r?\\n') to handle both. Remember that split() takes a regex, so the backslash is escaped.
What’s the difference between replace() and replaceAll()?
replace() replaces all literal occurrences of a substring, while replaceAll() treats the first argument as a regular expression. For example, 'a1b2'.replace('1','x') gives 'axb2', but 'a1b2'.replaceAll('[0-9]','x') gives 'axb x' (without spaces, actually ‘axbx’). Use replace() for simple text and replaceAll() for patterns.
How can I check if a string contains only numbers?
Use String.isNumeric() which returns true if the string consists only of digits (0-9). For decimal numbers, you might need a regex like '^\\d+(\\.\\d+)?$' with Pattern.matches().
Why does split() throw an error on a period?
Because split() expects a regular expression, and a period is a special character that matches any character. You must escape it as split('\\.') to split on a literal dot.
Can I use String methods in Flow?
Yes, but Flow uses its own formula syntax, not Apex. For example, you can use LEFT({!text}, 5) or CONTAINS({!text}, "abc"). For complex logic, you can invoke an Apex action from Flow.
How do I get the last character of a string?
Use myString.right(1) to get the last character, or myString.substring(myString.length()-1). right() is safer because it handles short strings gracefully.
Related
- Google Sheets VLOOKUP Multiple Columns: How To
- 6 Digit Random Number: How to Generate One
- STRING_SPLIT SQL Server Syntax & Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Horizontal Filter in Excel: How to Filter Across ColumnsTo filter data arranged across columns in Excel for Microsoft 365, use the FILTER function with a horizontal…
- Excel Goal Seeking: Find a Target Value with What-If ToolsExcel Goal Seek finds the input value that makes a formula return a result you specify. In Excel…
- Copy Values Without Formulas in Excel: Step-by-StepTo copy formula results without copying the formulas in Excel for Microsoft 365 on Windows, select the cells,…
- Filter by Month in Excel: Step-by-StepTo filter Excel dates to one particular month and year, open the date column’s filter menu and choose…
- SUBTOTAL Formula Shortcut: Insert It Quickly in ExcelIn Excel for Microsoft 365 on Windows, press Alt+= to run AutoSum, but this is not a dedicated…
- Count Unique Values in an Excel PivotTable: A Clear GuideTo count unique values in an Excel PivotTable, create the PivotTable with Add this data to the Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.