Swift Get string between 2 strings in a string

alp picture alp · Jul 30, 2015 · Viewed 31k times · Source

I am getting a string from html parse that is;

string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

my code is something like

var startIndex = text.rangeOfString("'")
var endIndex = text.rangeOfString("',")
var range2 = startIndex2...endIndex
substr= string.substringWithRange(range)

i am not sure if my second splitting string should be "'" or "',"

i want my outcome as

substr = "Info/99/something"

Answer

oisdk picture oisdk · Jul 30, 2015
extension String {
    
    func slice(from: String, to: String) -> String? {
        return (range(of: from)?.upperBound).flatMap { substringFrom in
            (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
                String(self[substringFrom..<substringTo])
            }
        }
    }
}

"javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"
  .sliceFrom("'", to: "',")