Jason Sturges Jason Sturges -4 years ago 140
Swift Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download