Skip to content

StringUtils.substringBeforeLast

Signature: StringUtils.substringBeforeLast(inputString, separator)

Returns: String result - the substring before the last occurrence of the separator, or null if inputString is null

Gets the substring before the last occurrence of a separator. The separator is not returned. A null inputString will return null. An empty ("") inputString will return the empty string. An empty or null separator will return the input string. If nothing is found, the input string is returned.

Parameters

Type Name Description Default
String inputString the String to get a substring from, may be null
String separator the String to search for, may be null

Example

// Typical usage: returns text before the LAST occurrence of the separator (separator not included)
StringUtils.substringBeforeLast("lion, and tiger, and bears, oh my!", ", ");   // lion, and tiger, and bears

// If the separator is not found, returns the original inputString
StringUtils.substringBeforeLast("lion, and tiger, and bears, oh my!", "not found"); // lion, and tiger, and bears, oh my!

// If inputString is empty, returns empty string
StringUtils.substringBeforeLast("", ", ");                                     // ""

// If inputString is null, returns null
StringUtils.substringBeforeLast(null, ", ");                                   // null

// If separator is empty or null, returns the original inputString
StringUtils.substringBeforeLast("lion, and tiger, and bears, oh my!", "");    // lion, and tiger, and bears, oh my!
StringUtils.substringBeforeLast("lion, and tiger, and bears, oh my!", null);  // lion, and tiger, and bears, oh my!