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
To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered.
Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.
To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.
To remove last character of a String in Swift, call removeLast() method on this string. String. removeLast() method removes the last character from the String.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With