How should I remove all the leading spaces from a string? - swift

ID : 20183

viewed : 12

Tags : stringswiftstring

Top 5 Answer for How should I remove all the leading spaces from a string? - swift

vote vote

95

To remove leading and trailing whitespaces:

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) 

Swift 3 / Swift 4:

let trimmedString = string.trimmingCharacters(in: .whitespaces) 
vote vote

80

The correct way when you want to remove all kinds of whitespaces (based on this SO answer) is:

extension String {     var stringByRemovingWhitespaces: String {         let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())         return components.joinWithSeparator("")     } } 

Swift 3.0+ (3.0, 3.1, 3.2, 4.0)

extension String {     func removingWhitespaces() -> String {         return components(separatedBy: .whitespaces).joined()     } } 

EDIT

This answer was posted when the question was about removing all whitespaces, the question was edited to only mention leading whitespaces. 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)).isSubset(of: .whitespaces) }) else {             return self         }         return String(self[index...])     } } 
vote vote

71

This String extension removes all whitespace from a string, not just trailing whitespace ...

 extension String {     func replace(string:String, replacement:String) -> String {         return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)     }      func removeWhitespace() -> String {         return self.replace(string: " ", replacement: "")     }   } 

Example:

let string = "The quick brown dog jumps over the foxy lady." let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady. 
vote vote

66

Swift 3

You can simply use this method to remove all normal spaces in a string (doesn't consider all types of whitespace):

let myString = " Hello World ! " let formattedString = myString.replacingOccurrences(of: " ", with: "") 

The result will be:

HelloWorld! 
vote vote

54

You can also use regex.

let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil) 

Top 3 video Explaining How should I remove all the leading spaces from a string? - swift

Related QUESTION?