Those who write in C # know very well and often use the String.Format mechanism, which is severely lacking in JavaScript. Despite its simplicity and convenience, there is little that can be dug up in the vastness of the Web, mainly variations on the theme of sprintf (hello to users). A script was written long ago that allowed formatting strings in JavaScript and was similar to String.Format C #. The formatting was started to be used by colleagues quite tightly in scripts and I decided to comb the code a bit and publish it for those who want to get String.Format in JavaScript.

    So, the main features:

    • Markers like in C #: {0}
    • You can specify the formatting function used: {0:d}
    • You can pass parameters to the formatting function: {0:n(,2)}
    • You can register your formatting functions
    • Small size - 3.5Kb in packed form
    • Works fast
    • Works in IE, Chrome, Firefox (verified), theoretically nothing prevents working in server-side JavaScript
    • Already implemented and built-in formatting functions:
      • Array Formatting
      • Number formatting
      • Formatting Date and Time


    You can use it in 2 ways:
    1. As in C #:
    var s = String.Format(format, arg0[, arg1[, arg2[...]]]);

    2. As a function of any line:
    var s = 'format string {0}'.format(arg0[, arg1[, arg2[...]]]);

    Rules for Tokens

    {0}- the value will be converted to a string according to the rules of JavaScript
    {0:f}- the value will be converted to a string using the function registered under the name f
    {0:f(p1,p2)}- the value will be converted to a string using the function registered under the name f and parameters p1 and p2 in the array will be transferred to this function, the number and the rules for the parameters depend on the function itself, however there are several general rules:
    1. Parameters separated by commas
    2. All characters in parentheses are significant i.e. for it {0:f(p1,p2)}will be transmitted ['p1', 'p2'], and in the case it {0:f(p1, p2)}will be transmitted ['p1', 'p2']
    3. To mask the comma and closing parenthesis, use the slash: it {0:f(p1\, p2)}will be transmitted ['p1, p2']
    4. Parameters can be skipped: for {0:f(,p2)}will be transmitted ['', 'p2']
    5. You can use nested tokens: for {0:f({1})}[[value_of_parameter_with_index_1_] will be passed], in this case formatting is not allowed, and the value is transferred the same as that passed to the format function

    Formatting functions

    All formatting functions receive 2 parameters: the value to be formatted and an array of parameters. This is how it is recommended to register formatting functions:
    (function(format)<br/>{<br/>    // Регистрация функции форматирования<br/>    // name   - имя для использования в маркерах<br/>    // v      - значение для форматирования, в функцию будет передано так же, как его передали в функцию format<br/>    // params - массив параметров, всегда есть, но межет быть нулевого размера<br/>    // Функция обязана вернуть строку, которая будет подставлена вместо метки<br/>    format.add(name, function(v, params)<br/>    {<br/>        return ...;<br/>    });<br/>})(String.prototype.format);

    Built-in formatting features

    The script already has formatting functions for numbers, arrays, and dates.

    {0:n}- formatting a number, if not a number has come to the function, then NaN will be displayed. The form of numbers 1.11111111e + 20 will be converted to normal: 111111111000000000000. You can transfer lines with the number: '1.67' or '123.456e + 2' - 1.67 and 12345.6 will be inserted, respectively.

    {0:n([i][,f])}- formatting a number filled with zeros to the desired number of digits.
    i - the number of digits for the integer part, if there are more digits in the integer part, then they remain in place, if less, the desired number of zeros will be inserted at the beginning.
    f - the number of digits for the fractional part, extra numbers will be discarded.
    Parameters can be skipped: {0: n (, 2)} - print a number with 2 digits in the decimal part.

    {0:df([f])} - arbitrary date formatting, f - format string with substitutions, possible substitutions:
    • yy or yyyy - Year, 4 characters are always displayed.
    • M or MM - Month, 1 or 2 digits
    • d or dd - Day, 1 or 2 digits
    • H or HH - Clock, 1 or 2 digits in 24-hour format
    • m or mm - Minutes, 1 or 2 digits
    • s or ss - Seconds, 1 or 2 digits
    • f ... ffff - Milliseconds, 1 to 4 characters

    More complete documentation where to download the script

    Actually, everything is here: a full description of the built-in formats, a test script, sources and a packaged version.

    The script does not require any additional libraries to work and is divided into 3 parts:
    1. Actually the implementation of the main formatting code
    2. Number formatting
    3. Date / Time Formatting

    To reduce the script, you can remove the second and (or) third parts from there.
    There are enough comments in the source to understand how it works.
    All code is colored using DmSyntax

    Also popular now: