如何删除带有特殊字符的 NSURL 的最后一个路径
How to remove last path of NSURL with special characters
所以我有点困惑。我有一个像这样的 NSURL
https://something/something/test#4.html
我想删除最后一条路径。我尝试使用 URLByDeletingLastPathComponent 方法,但结果是这样。
https://something/something/#4.html
我希望最终结果如下。
https://something/something
首先你必须删除片段。然后最后一个路径使用deletingLastPathComponent()
.
var url = URL(string: "https://something/something/test#4.html")
if let fragment = url?.fragment{
url = URL(string: (url?.absoluteString.replacingOccurrences(of: "#\(fragment)", with: ""))!)
url = url?.deletingLastPathComponent()
}
print(url!)
删除片段的聪明方法是URLComponents
let url = URL(string: "https://something/something/test#4.html")!
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
urlComponents.fragment = nil
let trimmedURL = urlComponents.url!.deletingLastPathComponent()
print(trimmedURL)
}
所以我有点困惑。我有一个像这样的 NSURL
https://something/something/test#4.html
我想删除最后一条路径。我尝试使用 URLByDeletingLastPathComponent 方法,但结果是这样。
https://something/something/#4.html
我希望最终结果如下。
https://something/something
首先你必须删除片段。然后最后一个路径使用deletingLastPathComponent()
.
var url = URL(string: "https://something/something/test#4.html")
if let fragment = url?.fragment{
url = URL(string: (url?.absoluteString.replacingOccurrences(of: "#\(fragment)", with: ""))!)
url = url?.deletingLastPathComponent()
}
print(url!)
删除片段的聪明方法是URLComponents
let url = URL(string: "https://something/something/test#4.html")!
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
urlComponents.fragment = nil
let trimmedURL = urlComponents.url!.deletingLastPathComponent()
print(trimmedURL)
}