Home > Software engineering >  How to remove last path of NSURL with special characters
How to remove last path of NSURL with special characters

Time:04-27

So I'm a little confused. I have an NSURL like this

https://something/something/test#4.html

I want to remove the last path of this. I tried using URLByDeletingLastPathComponent method but then it results in this.

https://something/something/#4.html

I want the end result to be the following.

https://something/something

CodePudding user response:

A smart way to remove the fragment is 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)
}

CodePudding user response:

First you have to remove the fragment. Then the last path using 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!)
  • Related