0

I have some of url string like:

let url1 = "https://abc/help?user_info_id=5#help-article03"

let url2 = "https://cde?user_info_id=455&artical=4"

let url3 = "https://ghi/help?user_info_id=5"

Now i want to get user_info_id from these urls.

url1 return 5, url2 return 455 and url3 return 5

This is my code

func getID(string: String) -> String {
    let range = string.rangeOfString("user_info_id=")
    guard let endIndex = range?.endIndex else { return "" }
    let remain = string.substringFromIndex(endIndex)

    let num = "0123456789"
    var result = ""
    for c in remain.characters {
        if num.containsString(String(c)) {
            result.append(c)
        } else {
            break
        }
    }
    return result
}

Please tell me your idea. Thank you!

2

1 Answer 1

4

Use (NS)URLComponents and filter the query items:

let url1 = "https://cde?user_info_id=455&artical=4"
if let components = NSURLComponents(string: url1),
  let queryItems = components.queryItems,
  let userInfoId = queryItems.filter({$0.name == "user_info_id"}).first where userInfoId.value != nil {
  print(userInfoId.value!)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.