Here is a version I wrote using split:
fileName.split('.').init ++ Seq("js") mkString "."
This transforms e.g. foo.bar.coffee
into foo.bar.js
.
What I like:
indexOf()
What I don't like:
How can I write an even simpler / straightforward version?
UPDATE: Great answers below! In short:
a slightly shorter syntax for the original approach (corner cases not covered) reads:
fileName.split('.').init :+ "js" mkString "."
Scala String replace() method with exampleThe replace() method is used to replace the old character of the string with the new one which is stated in the argument. Return Type: It returns the stated string after replacing the old character with the new one.
java“. The method getExtension(String) will check whether the given filename is empty or not. If filename is empty or null, getExtension(String filename) will return the instance it was given. Otherwise, it returns extension of the filename.
If you know what the current extension is, then you could do this:
def replaceExtension(fileName: String, oldExt: String, newExt: String): String =
fileName.stripSuffix(oldExt) + newExt
// Be sure to use `.` when calling:
replaceExtension(fileName, ".javascript", ".js")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With