Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
user1019042 Avatar asked Dec 31 '16 22:12

user1019042


People also ask

How do you remove trailing spaces in Swift?

To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.

How do you remove leading and trailing spaces from a string in Swift?

If you only want to remove leading whitespaces use the following: extension String { func removingLeadingSpaces() -> String { guard let index = firstIndex(where: { ! CharacterSet(charactersIn: String($0)).

How do you remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.


1 Answers

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)
like image 199
vadian Avatar answered Sep 20 '22 17:09

vadian