[英]C# String.Format equivalent is JS with customize formatter
There are different question regarding this issue, But they all cover the C# native String.Format method which cover cases like these, when only the index is replaced:关于这个问题有不同的问题,但它们都涵盖了 C# 原生 String.Format 方法,这些方法涵盖了这样的情况,当只替换索引时:
"{0}, {1}!', 'Hello', 'world"
In .Net i can implement IFormatProvider, ICustomFormatter
and provide it to在 .Net 中,我可以实现
IFormatProvider, ICustomFormatter
并将其提供给
String Format(IFormatProvider provider, String format, params object[] args);
And then format strings like:然后格式化字符串,如:
"{0:u} {0:l}"
And in the formatter implementation I have access to the format (in the example 'u' or 'l') and format the string accordingly by switch casing the format.在格式化程序实现中,我可以访问格式(在示例“u”或“l”中)并通过切换大小写格式来相应地格式化字符串。 How can I achieve this with JS
我怎样才能用 JS 实现这一点
C# Example: C# 示例:
public class CustomFormatter : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
switch (format)
{
case "u":
return (arg).ToUpperCase();
case "l":
return (arg).ToLowerCase();
}
}
}
string.Format(new CustomFormatter(),"{0:u} {1:l}","hello","WORLD")
//OUTPUT: "HELLO world"
Such a thing doesn't exist in Javascript, but you can use an external library to achieve a similar result. Javascript 中不存在这样的东西,但是您可以使用外部库来实现类似的结果。 For example using the package string-format you can do:
例如,使用包string-format您可以执行以下操作:
const fmt = format.create ({
lower: s => s.toLowerCase(),
upper: s => s.toUpperCase(),
})
fmt ('{!upper} {!lower}!', "hello","WORLD")
// 'HELLO world'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.