1

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"
ATT
  • 921
  • 3
  • 13
  • 30
  • Does this answer your question? [JavaScript equivalent to printf/String.Format](https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – Simone Rossaini Oct 17 '21 at 08:50
  • No, Its covering the example like ""0}, {1}!', 'Hello', 'world" – ATT Oct 17 '21 at 09:27

1 Answers1

0

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'
gcores
  • 12,376
  • 2
  • 49
  • 45