Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala expression to replace a file extension in a string

Tags:

scala

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:

  • it works
  • it doesn't rely on things like indexOf()
  • it feels functional ;)

What I don't like:

  • it's not as short as I would hope
  • it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

  • seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those
  • another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background
  • a slightly shorter syntax for the original approach (corner cases not covered) reads:

    fileName.split('.').init :+ "js" mkString "."

like image 652
ebruchez Avatar asked Jan 19 '11 01:01

ebruchez


People also ask

How to replace in Scala String?

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.

How do I get the file extension of a file in Java?

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.


1 Answers

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")
like image 101
Daniel C. Sobral Avatar answered Oct 30 '22 18:10

Daniel C. Sobral