436

Does Swift have a trim() method on String? For example:

let result = " abc ".trim() // result == "abc" 
2
  • 5
    @mattdipasquale trim is a very common name for this operation Commented Apr 12, 2016 at 17:14
  • 2024 - are you just looking for .prefix(13) ? Commented Feb 14, 2024 at 15:52

16 Answers 16

879

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" 
Sign up to request clarification or add additional context in comments.

7 Comments

Will not work on swif 1.2, as there is no automatic convention from String into NSString.
It works fine in Swift 1.2 - the String object has stringByTrimmingCharactersInSet method (it isn't an NSString exclusive)
In Swift 3.0 is: let trimmedString = myString.trimmingCharacters(in: .whitespaces)
That doesn't mean it is outdated. Not everyone is using Swift 3.0 yet.
In Swift 3.0 this will not remove white spaces in between string. It'll only remove leading and trailing white spaces. For that refer this answer: stackoverflow.com/a/39067610/4886069
|
154

Put this code on a file on your project, something likes Utils.swift:

extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespaces) } } 

So you will be able to do this:

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

6 Comments

Is that safe? How do I prevent a method name collision if Apple or some third party library adds the same method to String?
Extensions are safe - and in fact Apple makes prolific use of them in their internal APIs. You cannot prevent any name collisions, and this is in fact good. You will get a compile error when Apple does finally add a trim() method and you will know that your extension is no longer required. Extensions are quite elegant and put methods where you need them rather than some obscure utility class like StringUtils - the problem I have is when a class doesn't have a method I need because some other framework wasn't imported that added extensions to it.
Hey, in Swift 3 should be return return self.trimmingCharacters(in: .whitespacesAndNewlines)
let result = " Hello World ".trim() // result = "HelloWorld" this will not remove the whitespaces contained in string. will remve only leading and trailing spaces.
this will not remove spaces in between string. It only removes leading and trailing space. So better way to remove spaces in between string is use yourtext?.replacingOccurrences(of: " ", with: "") instead of using trimmingCharacters
|
65

In Swift 3.0

extension String { func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } } 

And you can call

let result = " Hello World ".trim() /* result = "Hello World" */ 

4 Comments

What if I only want to trim trailing and leading whitespace?
I'm new to swift 3 extensions. If a library modifies String, and I also modify String, is it possible to get collisions? What if future versions of swift ad a trim() method? So.. basically.. are extensions safe to use like this?
it's possible to get collisions.
let result = " Hello World ".trim() // result = "HelloWorld" this will not remove the whitespaces contained in string. will remve only leading and trailing spaces
58

Swift 5 & 4.2

let trimmedString = " abc ".trimmingCharacters(in: .whitespaces) //trimmedString == "abc" 

Comments

21

Swift 3

let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines) 

3 Comments

@LucasFarah see swift-evolution
Expected release date: Late 2016
It's actually "whitespacesAndNewlines", haha, one 's' left.
13

Yes it has, you can do it like this:

var str = " this is the answer " str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) print(srt) // "this is the answer" 

CharacterSet is actually a really powerful tool to create a trim rule with much more flexibility than a pre defined set like .whitespacesAndNewlines has.

For Example:

var str = " Hello World !" let cs = CharacterSet.init(charactersIn: " !") str = str.trimmingCharacters(in: cs) print(str) // "Hello World" 

Comments

6

//Swift 4.0 Remove spaces and new lines

extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } } 

Comments

4
extension String { /// EZSE: Trims white space and new line characters public mutating func trim() { self = self.trimmed() } /// EZSE: Trims white space and new line characters, returns a new string public func trimmed() -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } 

Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206

1 Comment

I like the swift compliant verb-ing for non mutating.
4

In Swift3 XCode 8 Final

Notice that the CharacterSet.whitespaces is not a function anymore!

(Neither is NSCharacterSet.whitespaces)

extension String { func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } } 

Comments

4

Another similar way:

extension String { var trimmed:String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } } 

Use:

let trimmedString = "myString ".trimmed 

Comments

4

Truncate String to Specific Length

If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class

extension String { func trunc(_ length: Int) -> String { if self.characters.count > length { return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) } else { return self } } func trim() -> String{ return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } 

Use

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." //str is length 74 print(str) //O/P: Lorem Ipsum is simply dummy text of the printing and typesetting industry. str = str.trunc(40) print(str) //O/P: Lorem Ipsum is simply dummy text of the 

1 Comment

Doesn't answer the question.
3

You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.

var string = "hello " var trimmed = string.trim() println(trimmed)// "hello" 

1 Comment

looks nice. I'll use that.
2

You can also send characters that you want to be trimed

extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } func trim(characterSet:CharacterSet) -> String { return self.trimmingCharacters(in: characterSet) } } validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ",")) 

Comments

0

I created this function that allows to enter a string and returns a list of string trimmed by any character

 func Trim(input:String, character:Character)-> [String] { var collection:[String] = [String]() var index = 0 var copy = input let iterable = input var trim = input.startIndex.advancedBy(index) for i in iterable.characters { if (i == character) { trim = input.startIndex.advancedBy(index) // apennding to the list collection.append(copy.substringToIndex(trim)) //cut the input index += 1 trim = input.startIndex.advancedBy(index) copy = copy.substringFromIndex(trim) index = 0 } else { index += 1 } } collection.append(copy) return collection } 

as didn't found a way to do this in swift (compiles and work perfectly in swift 2.0)

1 Comment

can you define what you mean by 'trim', with an example. Since your return type is [String] you cannot be implementing what the OP requested. (which returns a String)
0

Don't forget to import Foundation or UIKit.

import Foundation let trimmedString = " aaa "".trimmingCharacters(in: .whitespaces) print(trimmedString) 

Result:

"aaa" 

Otherwise you'll get:

error: value of type 'String' has no member 'trimmingCharacters' return self.trimmingCharacters(in: .whitespaces) 

Comments

0
**Swift 5** extension String { func trimAllSpace() -> String { return components(separatedBy: .whitespacesAndNewlines).joined() } func trimSpace() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } } **Use:** let result = " abc ".trimAllSpace() // result == "abc" let ex = " abc cd ".trimSpace() // ex == "abc cd" 

1 Comment

Please don't post "code only" answers. Add some description or comments in the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.