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:
"{0}, {1}!', 'Hello', 'world"
In .Net i can implement IFormatProvider, ICustomFormatter and provide it to
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. How can I achieve this with JS
C# Example:
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. For example using the package string-format you can do:
const fmt = format.create ({
lower: s => s.toLowerCase(),
upper: s => s.toUpperCase(),
})
fmt ('{!upper} {!lower}!', "hello","WORLD")
// 'HELLO world'