Search code examples
iosswiftstringsubstringstring-comparison

iOS Swift - How to match a string that is "like" another string? i.e. "http" is like "http://"


I created a URL Validation function that validates for URL as text is entered by a user into a text field.

However, in an effort 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 "smartly" ignore text that may MATCH 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 may match provided prefixes but not necessarily are equal?


Solution

  • Ok, figured it out. Had to use 'rangeOfString' function and check if user's 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
            }
        }