IOS Swift - How to match a string that "looks like" another string? those. "http" is like "http: //"
I created a url validator function that validates the url as text is entered by the user into the textbox.
However, to save performance and memory, I want to ignore entries that may contain common URL prefixes:
(i.e. http://, http://www, www, etc)
With that said, I want to be able to "cleverly" ignore text that might CONNECT one of these URL prefixes:
["http://www", "https://www", "www"]
i.e. If a user has typed "htt", it should be ignored since it is a substring of "http://www" or "https://www"
What is the best way to check if a string can match the specified prefixes, but not necessarily equal?
+3
source to share
2 answers
Okay, got it. Had to use the rangeOfString function and check if the user text was in my control text.
Code:
let prefixes = ["http://www.", "https://www.", "www."]
for prefix in prefixes
{
if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
completion(success: false, urlString: nil, error: "Url String was prefix only")
return
}
}
0
source to share
In the Quick Programming Guide, you can use the hasPrefix method.
Example:
if userString.hasPrefix("http") {
// do something with userString
}
Source: Swift Programming Language Guide
+1
source to share