Skip to content

Instantly share code, notes, and snippets.

@fbaierl
Created October 25, 2018 07:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbaierl/ade57727698a23b709d55441d7b9dfd3 to your computer and use it in GitHub Desktop.
Save fbaierl/ade57727698a23b709d55441d7b9dfd3 to your computer and use it in GitHub Desktop.
Scala.js string interpolation like java.text.MessageFormat
object Format {
/**
* String interpolation [[java.text.MessageFormat]] style:
* {{{
* format("{1} {0}", "world", "hello") // result: "hello world"
* format("{0} + {1} = {2}", 1, 2, "three") // result: "1 + 2 = three"
* format("{0} + {0} = {0}", 0) // throws MissingFormatArgumentException
* }}}
* @return
*/
def format (text: String, args: Any*): String = {
var scalaStyled = text
val pattern = """{\d+}""".r
pattern.findAllIn(text).matchData foreach {
m => val singleMatch = m.group(0)
var number = singleMatch.substring(1, singleMatch.length - 1).toInt
// %0$s is not allowed so we add +1 to all numbers
number = 1 + number
scalaStyled = scalaStyled.replace(singleMatch, "%" + number + "$s")
}
scalaStyled.format(args:_*)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment