2017-10-09 47 views
-1

我有一個類似於myapp://jhb/test/deeplink/url?id=4567的URL。 我想刪除? char之後的所有東西。最後,URL應該看起來像myapp://jhb/test/deeplink/url。怎麼樣。我可以做到嗎?將網址轉換爲字符串?正則表達式?使用swift從URL中刪除參數

+0

只是看看這一個https://stackoverflow.com/questions/39184984/delete-all-characters-after-a-certain-character-from-a-string-in-swift –

回答

0

你可以這樣做

let values = utl?.components(separatedBy: "?")[0] 

這將打破串?並返回數組。 values的第一個對象給你你的結果字符串。

0

你可以使用

print("\(url.host!)") //Domain name 
print("\(url.path)") // Path 
print("\(url.query)") // query string 
0

使用URLComponents不同的URL部分分開,處理它們,然後提取新的URL從以下網址分隔每個URL部分:

var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567")! 
components.query = nil 
print(components.url!) 

myapp://jhb/test/deeplink/url

0

我可以做到嗎?將網址轉換爲字符串?正則表達式?

當使用URL,倒不如把它當作URLComponent

該網址解析成和結構的網址從他們 組成部分的結構。

因此,參照URLComponent什麼是你問的是從URL中刪除的query子:

if var componenets = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567") { 
    componenets.query = nil 

    print(componenets) // myapp://jhb/test/deeplink/url 
} 

注意query可選字符串,這意味着它可能是零(如代碼片段中所述,這應該會導致您所需的輸出)。