Home > Back-end >  Get a part of a string that comes before .mp3 but is not always the same link
Get a part of a string that comes before .mp3 but is not always the same link

Time:07-07

I want to get only the ID that comes before the .mp3 but after several attempts I can't do it, the link is not always the same length

String examples:

"https://urlexample.com/EXAMPLE_STRING/media/example/audio/20227/07/1657142074431_15789.mp3"
"https://urlexample.com/media/THIS_TEXT_IS_1657130179082_24048.mp3"

The result should be:

"https://urlexample.com/audio/1657130179082_24048"
"https://urlexample.com/audio/THIS_TEXT_IS_1657130179082_24048"

If anyone can help I would appreciate it.

CodePudding user response:

Create a URL with your string then get the id

Code :

let string = "https://urlexample.com/EXAMPLE_STRING/media/example/audio/20227/07/1657142074431_15789.mp3"

guard let url = URL(string: string) else {
    // not a url string
    return
}
  
// file name with extension  
let fileName = url.lastPathComponent
print(fileName) // 1657142074431_15789.mp3

// file id 
let fileId = url.deletingPathExtension().lastPathComponent
print(fileId) // 1657142074431_15789
  • Related