I have a textField
and I would like to remove all character after a certain character.
For instance if what I have in the textField is the word Orange
and I want to remove all characters after the n
I would like to get Ora
after the deletion.
How can I delete all characters after a certain character from a string in Swift?
Thanks
You can use StringProtocol
method range(of string:)
, get the resulting range lowerBound, create a PartialRangeUpTo
with it and subscript the original string:
Swift 4 or later
let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
let substring = word[..<index] // "ora"
// or let substring = word.prefix(upTo: index) // "ora"
// (see picture below) Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection’s subscript.
// The subscript notation is preferred over prefix(upTo:).
let string = String(substring)
print(string) // "ora"
}
You could do it like this:
guard let range = text.rangeOfString("Your String or Character here") else {
return the text
}
return text.substringToIndex(range.endIndex)
// depending on if you want to delete before a certain string, you would use range.startIndex
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