So I have an image URL:
https://images.gr-assets.com/books/1410762334m/135625.jpg
replacingOccurrences(of: "m", with: "l", options: .literal, range: nil)
You should use NSRegularExpression
for this.
m
and a slash (/
). m
in only that range and replaces it with an l
.let urlString: NSString = "https://images.gr-assets.com/books/1410762334m/135625.jpg"
do {
let regex = try NSRegularExpression(pattern: "[0-9]m/", options: .caseInsensitive)
let fullRange = NSMakeRange(0, urlString.length)
let matchRange = regex.rangeOfFirstMatch(in: urlString as String, options: [], range: fullRange)
let modString = urlString.replacingOccurrences(of: "m", with: "l", options: .caseInsensitive, range: matchRange)
} catch let error {
//NSRegularExpression threw an error; handle it properly
print(error.localizedDescription)
}
Swift 4
let urlString = "https://images.gr-assets.com/books/1410762334m/135625.jpg"
do {
let regex = try NSRegularExpression(pattern: "[0-9]m/", options: .caseInsensitive)
let fullRange = NSMakeRange(0, urlString.count)
let matchRange = regex.rangeOfFirstMatch(in: urlString, options: [], range: fullRange)
let modString = urlString.replacingOccurrences(of: "m", with: "l", options: .caseInsensitive, range: Range(matchRange, in: urlString))
} catch let error {
//NSRegularExpression threw an error; handle it properly
print(error.localizedDescription)
}