Delete all characters after a certain character from a string in Swift
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
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"
}