Remove suffix from filename in Swift Remove suffix from filename in Swift swift swift

Remove suffix from filename in Swift


If by suffix you mean path extension, there is a method for this:

let filename = "demoArt.png"let name = (filename as NSString).deletingPathExtension// name - "demoArt"


Some people here seem to overlook that a filename can have multiple periods in the name and in that case only the last period separates the file extension. So this.is.a.valid.image.filename.jpg and stripping the extension should return this.is.a.valid.image.filename and not this (as two answers here would produce) or anything else in between. The regex answer works correctly but using a regex for that is a bit overkill (probably 10 times slower than using simple string processing). Here's a generic function that works for everyone:

func stripFileExtension ( _ filename: String ) -> String {    var components = filename.components(separatedBy: ".")    guard components.count > 1 else { return filename }    components.removeLast()    return components.joined(separator: ".")}print("1: \(stripFileExtension("foo"))")print("2: \(stripFileExtension("foo.bar"))")print("3: \(stripFileExtension("foo.bar.foobar"))")

Output:

foofoofoo.bar


You can also split the String using componentsSeparatedBy, like this:

let fileName = "demoArt.png"var components = fileName.components(separatedBy: ".")if components.count > 1 { // If there is a file extension  components.removeLast()  return components.joined(separator: ".")} else {  return fileName}

To clarify:

fileName.components(separatedBy: ".")

will return an array made up of "demoArt" and "png".