JavaScript equivalent to printf/String.Format

前端 未结 30 2381
囚心锁ツ
囚心锁ツ 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条回答
  • 2020-11-21 05:10

    From ES6 on you could use template strings:

    let soMany = 10;
    console.log(`This is ${soMany} times easier!`);
    // "This is 10 times easier!
    

    Be aware that template strings are surrounded by backticks ` instead of (single) quotes.

    For further information:

    https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

    Note: Check the mozilla-site to find a list of supported browsers.

    0 讨论(0)
  • 2020-11-21 05:10

    I'm surprised no one used reduce, this is a native concise and powerful JavaScript function.

    ES6 (EcmaScript2015)

    String.prototype.format = function() {
      return [...arguments].reduce((p,c) => p.replace(/%s/,c), this);
    };
    
    console.log('Is that a %s or a %s?... No, it\'s %s!'.format('plane', 'bird', 'SOman'));

    < ES6

    function interpolate(theString, argumentArray) {
        var regex = /%s/;
        var _r=function(p,c){return p.replace(regex,c);}
        return argumentArray.reduce(_r, theString);
    }
    
    interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"
    

    How it works:

    reduce applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    var _r= function(p,c){return p.replace(/%s/,c)};
    
    console.log(
      ["a", "b", "c"].reduce(_r, "[%s], [%s] and [%s]") + '\n',
      [1, 2, 3].reduce(_r, "%s+%s=%s") + '\n',
      ["cool", 1337, "stuff"].reduce(_r, "%s %s %s")
    );

    0 讨论(0)
  • 2020-11-21 05:10

    JavaScript programmers can use String.prototype.sprintf at https://github.com/ildar-shaimordanov/jsxt/blob/master/js/String.js. Below is example:

    var d = new Date();
    var dateStr = '%02d:%02d:%02d'.sprintf(
        d.getHours(), 
        d.getMinutes(), 
        d.getSeconds());
    
    0 讨论(0)
  • 2020-11-21 05:14

    Number Formatting in JavaScript

    I got to this question page hoping to find how to format numbers in JavaScript, without introducing yet another library. Here's what I've found:

    Rounding floating-point numbers

    The equivalent of sprintf("%.2f", num) in JavaScript seems to be num.toFixed(2), which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math.round below).

    (12.345).toFixed(2); // returns "12.35" (rounding!)
    (12.3).toFixed(2); // returns "12.30" (zero padding)
    

    Exponential form

    The equivalent of sprintf("%.2e", num) is num.toExponential(2).

    (33333).toExponential(2); // "3.33e+4"
    

    Hexadecimal and other bases

    To print numbers in base B, try num.toString(B). JavaScript supports automatic conversion to and from bases 2 through 36 (in addition, some browsers have limited support for base64 encoding).

    (3735928559).toString(16); // to base 16: "deadbeef"
    parseInt("deadbeef", 16); // from base 16: 3735928559
    

    Reference Pages

    Quick tutorial on JS number formatting

    Mozilla reference page for toFixed() (with links to toPrecision(), toExponential(), toLocaleString(), ...)

    0 讨论(0)
  • 2020-11-21 05:16

    For Node.js users there is util.format which has printf-like functionality:

    util.format("%s world", "Hello")
    
    0 讨论(0)
  • 2020-11-21 05:16

    I want to share my solution for the 'problem'. I haven't re-invented the wheel but tries to find a solution based on what JavaScript already does. The advantage is, that you get all implicit conversions for free. Setting the prototype property $ of String gives a very nice and compact syntax (see examples below). It is maybe not the most efficient way, but in most cases dealing with output it does not have to be super optimized.

    String.form = function(str, arr) {
        var i = -1;
        function callback(exp, p0, p1, p2, p3, p4) {
            if (exp=='%%') return '%';
            if (arr[++i]===undefined) return undefined;
            exp  = p2 ? parseInt(p2.substr(1)) : undefined;
            var base = p3 ? parseInt(p3.substr(1)) : undefined;
            var val;
            switch (p4) {
                case 's': val = arr[i]; break;
                case 'c': val = arr[i][0]; break;
                case 'f': val = parseFloat(arr[i]).toFixed(exp); break;
                case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;
                case 'e': val = parseFloat(arr[i]).toExponential(exp); break;
                case 'x': val = parseInt(arr[i]).toString(base?base:16); break;
                case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;
            }
            val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);
            var sz = parseInt(p1); /* padding size */
            var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */
            while (val.length<sz) val = p0 !== undefined ? val+ch : ch+val; /* isminus? */
           return val;
        }
        var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;
        return str.replace(regex, callback);
    }
    
    String.prototype.$ = function() {
        return String.form(this, Array.prototype.slice.call(arguments));
    }
    

    Here are a few examples:

    String.format("%s %s", [ "This is a string", 11 ])
    console.log("%s %s".$("This is a string", 11))
    var arr = [ "12.3", 13.6 ]; console.log("Array: %s".$(arr));
    var obj = { test:"test", id:12 }; console.log("Object: %s".$(obj));
    console.log("%c", "Test");
    console.log("%5d".$(12)); // '   12'
    console.log("%05d".$(12)); // '00012'
    console.log("%-5d".$(12)); // '12   '
    console.log("%5.2d".$(123)); // '  120'
    console.log("%5.2f".$(1.1)); // ' 1.10'
    console.log("%10.2e".$(1.1)); // '   1.10e+0'
    console.log("%5.3p".$(1.12345)); // ' 1.12'
    console.log("%5x".$(45054)); // ' affe'
    console.log("%20#2x".$("45054")); // '    1010111111111110'
    console.log("%6#2d".$("111")); // '     7'
    console.log("%6#16d".$("affe")); // ' 45054'
    
    0 讨论(0)
提交回复
热议问题