I'm afraid that you really need to do this longer to do what is probably the most sensible thing:
scala> "oops".split('.').init ++ Seq("js") mkString "." res0: String = js
It is unusual to lose the name of your file (at least if you are an end user)!
Let try regex:
scala> "oops".replaceAll("\\.[^.]*$", ".js") res1: java.lang.String = oops
I did not lose the file name, but there was also no extension. Ack.
Let me fix it:
def extensor(orig: String, ext: String) = (orig.split('.') match { case xs @ Array(x) => xs case y => y.init }) :+ "js" mkString "." scala> extensor("oops","js") res2: String = oops.js scala> extensor("oops.txt","js") res3: String = oops.js scala> extensor("oops...um...","js") res4: String = oops...js
Or with regex:
scala> "oops".replaceAll("\\.[^.]*$", "") + ".js" res5: java.lang.String = oops.js scala> "oops.txt".replaceAll("\\.[^.]*$", "") + ".js" res6: java.lang.String = oops.js scala> "oops...um...".replaceAll("\\.[^.]*$", "") + ".js" res7: java.lang.String = oops...um...js
(Note the different behavior when the file name ends with a period.)
Rex kerr
source share