stringswift3nscharacterset

Swift remove ONLY trailing spaces from string


many examples in SO are fixing both sides, the leading and trailing. My request is only about the trailing. My input text is: " keep my left side " Desired output: " keep my left side"

Of course this command will remove both ends:

let cleansed = messageText.trimmingCharacters(in: .whitespacesAndNewlines)

Which won't work for me.

How can I do it?


Solution

  • A quite simple solution is regular expression, the pattern is one or more(+) whitespace characters(\s) at the end of the string($)

    let string = " keep my left side "
    let cleansed = string.replacingOccurrences(of: "\\s+$", 
                                             with: "", 
                                          options: .regularExpression)