javascript - scala.js 的字符串插值,如 java.text.MessageFormat
问题描述
我需要像java.text.MessageFormat
scala.js 这样的字符串插值。具体来说,我需要一些东西来让我为我们的翻译选择打印参数的顺序(如“{0}”、“{1}”)。
我想要的是:
val world = "world"
format("Hello {0}", world)
format("Hello {1}{0}", "!", world) // should print: "Hello world!"
我不能使用的:
"Hello $world"
"Hello %s".format(world)
有什么我可以使用但还没有找到的吗?为了一致性,我肯定更喜欢在我的字符串中使用'{x}'。
编辑:
使用 sjrd 的回答,我想出了以下内容:
/**
* 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:_*)
}
解决方案
您可以使用String.format
显式索引:
val world = "world"
"Hello %1$s".format(world)
"Hello %2$s%1$s".format("!", "world")
显式索引在 a 之前指定$
。它们是基于 1 的。
它不如. {x}
_ {x}
_%x$s
format
推荐阅读
- latex - 如何将特定小节中的文本更改为斜体?
- javascript - 从 setTimeout 调用 setState 会导致文本字段光标意外跳转
- java - 强制 ServerSocket 使用 IPv4
- excel - Excel VBA - 在标记为 3 个字符长度的工作表中过滤
- dotnetnuke - DNN 注册链接未显示
- node.js - 如何仅使用 Apollo Server 2 graphql 端点的快速中间件
- html - CSS - 当 HTML 元素包含另一个特定类时定位伪元素
- typescript - 打字稿编译器错误地假设错误值
- sensenet - 在本地主机上安装 Sensenet
- spring-boot - Flux 响应而不是 WebSocket (Spring boot)