Search code examples
swiftstringswift3

Trim only trailing whitespace from end of string in Swift 3


Every example of trimming strings in Swift remove both leading and trailing whitespace, but how can only trailing whitespace be removed?

For example, if I have a string:

"    example  "

How can I end up with:

"    example"

Every solution I've found shows trimmingCharacters(in: CharacterSet.whitespaces), but I want to retain the leading whitespace.

RegEx is a possibility, or a range can be derived to determine index of characters to remove, but I can't seem to find an elegant solution for this.


Solution

  • With regular expressions:

    let string = "    example  "
    let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
    print(">" + trimmed + "<")
    // >    example<
    

    \s+ matches one or more whitespace characters, and $ matches the end of the string.