sprintf equivalent for client-side JavaScript

后端 未结 2 1587
长情又很酷
长情又很酷 2020-12-19 16:50

I know that console.log supports at least some of the basic features of printf from C through messing around, but I was curious of a way to take ad

2条回答
  •  忘掉有多难
    2020-12-19 17:15

    Keep it simple

    var sprintf = (str, ...argv) => !argv.length ? str : 
        sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);
    

    Since Javascript handles data types automatically, there is no need for type options.

    If you need padding, "15".padStart(5,"0") = ("00000"+15).slice(-5) = "00015".

    Usage

    var sprintf = (str, ...argv) => !argv.length ? str : 
        sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);
    
    alert(sprintf("Success after $ clicks ($ seconds).", 15, 4.569));
    sprintf.token = "_";
    alert(sprintf("Failure after _ clicks (_ seconds).", 5, 1.569));
    
    sprintf.token = "%";
    var a = "%
    %
    %"; var b = sprintf("% plus % is %", 0, 1, 0 + 1); var c = sprintf("Hello, %!", "world"); var d = sprintf("The answer to everything is %.", 42); document.write(sprintf(a,b,c,d));

提交回复
热议问题