Does swift have a trim method on String?

tounaobun picture tounaobun · Nov 7, 2014 · Viewed 189.8k times · Source

Does swift have a trim method on String? For example:

let result = " abc ".trim()
// result == "abc"

Answer

Sivanraj M picture Sivanraj M · Nov 7, 2014

Here's how you remove all the whitespace from the beginning and end of a String.

(Example tested with Swift 2.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"

(Example tested with Swift 3+.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"