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?
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.
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)).
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With