JavaScript equivalent to printf/String.Format

前端 未结 30 2565
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

30条回答
  •  Happy的楠姐
    2020-11-21 05:05

    We can use a simple lightweight String.Format string operation library for Typescript.

    String.Format():

    var id = image.GetId()
    String.Format("image_{0}.jpg", id)
    output: "image_2db5da20-1c5d-4f1a-8fd4-b41e34c8c5b5.jpg";
    

    String Format for specifiers:

    var value = String.Format("{0:L}", "APPLE"); //output "apple"
    
    value = String.Format("{0:U}", "apple"); // output "APPLE"
    
    value = String.Format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"
    
    
    value = String.Format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"
    
    value = String.Format("{0:n}", 1000000);
    //output "1.000.000"
    
    value = String.Format("{0:00}", 1);
    //output "01"
    

    String Format for Objects including specifiers:

    var fruit = new Fruit();
    fruit.type = "apple";
    fruit.color = "RED";
    fruit.shippingDate = new Date(2018, 1, 1);
    fruit.amount = 10000;
    
    String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
    // output: the APPLE is red shipped on 2018-01-01 with an amount of 10.000
    

提交回复
热议问题