Delete all characters after a certain character from a string in Swift

2 Solutions Collect From Internet About “Delete all characters after a certain character from a string in Swift”

You can use rangeOfString and substringToIndex to its startIndex as follow:

Swift 2

let word = "orange"
if let index = word.rangeOfString("n")?.startIndex {
    print(word.substringToIndex(index))  // "ora"
}

Swift 3

let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
    print(word.substring(to: index))  // "ora"
}

Swift 4

let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
    let substring = word[..<index]
    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