33

I have a string like this:

"

BLA
Blub"

Now I would like to remove all leading line breaks. (But only the ones until the first "real word" appears. How is this possible?

Thanks

jscs
  • 63,694
  • 13
  • 151
  • 195
Christian
  • 6,961
  • 10
  • 54
  • 82

6 Answers6

70

If it is acceptable that newline (and other whitespace) characters are removed from both ends of the string then you can use

let string = "\n\nBLA\nblub"
let trimmed = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// In Swift 1.2 (Xcode 6.3):
let trimmed = (string as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

To remove leading newline/whitespace characters only you can (for example) use a regular expression search and replace:

let trimmed = string.stringByReplacingOccurrencesOfString("^\\s*",
    withString: "", options: .RegularExpressionSearch)

"^\\s*" matches all whitespace at the beginning of the string. Use "^\\n*" to match newline characters only.

Update for Swift 3 (Xcode 8):

let trimmed = string.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
19

You can use extension for Trim

Ex.

let string = "\n\nBLA\nblub"
let trimmed = string.trim()

extension String {
    func trim() -> String {
          return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
}
Jack
  • 13,571
  • 6
  • 76
  • 98
0

The trimming function wasn't working for me but this works. I am just replacing the next line "\n" with a blank space

func removeNextLineString(name: String) -> String{
    var newName = name
    newName = newName.replacingOccurrences(of: "\n", with: " ")
    
    return newName
}
STerrier
  • 3,755
  • 1
  • 16
  • 41
0

This will remove all leading new lines (carriage returns)

extension String {
    func trimLeadingNewLines() -> String {
        guard let firstIndex = indices.first, let lastIndex = indices.last else { return self }
        let firstCharIndex = self.firstIndex(where: { !$0.isNewline }) ?? firstIndex
        return String(self[firstCharIndex ... lastIndex])
    }
}
Jack
  • 2,503
  • 1
  • 21
  • 15
0

Swift 5 / Xcode 14.2:

extension String {
    func removeNewLines(_ delimiter: String = "") -> String {
        self.replacingOccurrences(of: "\n", with: delimiter)
    }
}

Usage:

let string = "Hello World\nHello World"
print(string)
/*
Prints
Hello World
Hello World
*/
print(string.removeNewLines())
/*
Prints
Hello WorldHello World
*/

print(string.removeNewLines(" "))
/*
Prints
Hello World Hello World
*/
tww0003
  • 801
  • 9
  • 18
0

###Swift 5.5

let trimmed = content.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
Ramis
  • 13,985
  • 7
  • 81
  • 100