How can I remove the first n characters from a string in swift?
How can I remove the first n characters from a string in swift?
I've tried many options but I can't solve it. I've URLs of differents sizes within string variables. I need just remove the http:// from them. How can I do it in Swift?
URL
String
Thanks for your recommendation. In my case I have the URLs in an array configured with them manually by me. Then, I make connection test to these URLs and finally I need remove the http:// from them to show them in the screen. It is something simple and without risk I think. I will take your recommendation in any case.
– Sebastian Diaz
Jun 30 at 1:11
2 Answers
2
Instead of removing n characters you maybe want to specifically check for http(s)://
:
http(s)://
let string = "https://www.google.de"
let newString = str.replacingOccurrences(of: "https?://", with: "", options: .regularExpression, range: nil)
Or:
var str = "https://www.google.de"
if let httpRange = str.range(of: "https?://", options: .regularExpression, range: nil, locale: nil) {
str.removeSubrange(httpRange)
}
Thanks André for your answer. I've implemented the Sandeep's answer first that is shorter.
– Sebastian Diaz
Jun 29 at 15:36
It may be shorter but it's less safe.
– Duncan C
Jun 29 at 15:44
To most reliably remove the scheme from the URL, I would avoid hard coding the scheme:
import Foundation
let url = URL(string: "http://google.com")!
var string = url.absoluteString
if let scheme = url.scheme, string.hasPrefix(scheme) {
string.removeFirst(scheme.count + "://".count)
}
print(string)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Don't work with URLs as strings. De-serialize them into
URL
instances as soon as you get them, and re-serialize them back intoString
instances at the last possible moment. Doing raw string manipulations to work with URLs is incredibly error prone, and frankly, it's just reinventing the wheel.– Alexander
Jun 29 at 17:44