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
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)
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)
}
}
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
}
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])
}
}
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
*/
###Swift 5.5
let trimmed = content.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)