JavaScript эквивалентен printf / String.Format - PullRequest
1785 голосов
/ 04 марта 2009

Я ищу хороший JavaScript-эквивалент C / PHP printf() или для программистов на C # / Java, String.Format() (IFormatProvider для .NET).

Мое основное требование на данный момент - это формат разделителя тысяч для чисел, но то, что обрабатывает множество комбинаций (включая даты), будет хорошо.

Я понимаю, что Microsoft Ajax предоставляет версию String.Format(), но нам не нужны все издержки этой инфраструктуры.

Ответы [ 45 ]

2 голосов
/ 25 июля 2014

Я не увидел pyformat в списке, поэтому я решил добавить:

console.log(pyformat( 'The {} {} jumped over the {}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {0} {1} jumped over the {1}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
                , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
                ))
2 голосов
/ 03 января 2016
/**
 * Format string by replacing placeholders with value from element with
 * corresponsing index in `replacementArray`.
 * Replaces are made simultaneously, so that replacement values like
 * '{1}' will not mess up the function.
 *
 * Example 1:
 * ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three'
 *
 * Example 2:
 * ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}'
 */
function stringFormat(formatString, replacementArray) {
    return formatString.replace(
        /\{(\d+)\}/g, // Matches placeholders, e.g. '{1}'
        function formatStringReplacer(match, placeholderIndex) {
            // Convert String to Number
            placeholderIndex = Number(placeholderIndex);

            // Make sure that index is within replacement array bounds
            if (placeholderIndex < 0 ||
                placeholderIndex > replacementArray.length - 1
            ) {
                return placeholderIndex;
            }

            // Replace placeholder with value from replacement array
            return replacementArray[placeholderIndex];
        }
    );
}
1 голос
/ 24 апреля 2018

Используя Lodash , вы можете получить функциональность шаблона:

Используйте литеральный разделитель шаблона ES в качестве «интерполяционного» разделителя. Отключите поддержку, заменив разделитель «интерполяция».

var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!
1 голос
/ 13 июня 2011

arg функция:

/**
 * Qt stil arg()
 * var scr = "<div id='%1' class='%2'></div>".arg("mydiv").arg("mydivClass");
 */
String.prototype.arg = function() {
    var signIndex = this.indexOf("%");
    var result = this;
    if (signIndex > -1 && arguments.length > 0) {
        var argNumber = this.charAt(signIndex + 1);
        var _arg = "%"+argNumber;
        var argCount = this.split(_arg);
        for (var itemIndex = 0; itemIndex < argCount.length; itemIndex++) {
            result = result.replace(_arg, arguments[0]);
        }
    }
    return result;
}
1 голос
/ 20 июля 2011

Существует также Globalize.format в проекте jQuery Globalize , официальной службе глобализации для пользовательского интерфейса jQuery. Это хорошо, когда вам нужно культурно-ориентированное форматирование.

1 голос
/ 01 августа 2013

Мне нужна была функция, которая могла бы отформатировать цену (указанную в центах) способом, предпочтительным для пользователя, и сложность заключается в том, что формат указан пользователем - и я не ожидаю, что мои пользователи поймут printf -подобный синтаксис или регулярные выражения и т. д. Мое решение несколько похоже на то, которое используется в Basic, поэтому пользователь просто помечает # местами для цифр, например:

simple_format(1234567,"$ ###,###,###.##")
"$ 12,345.67"
simple_format(1234567,"### ### ###,## pln")
"12 345,67 pln"

Я полагаю, что это довольно легко понять пользователю и довольно просто реализовать:

function simple_format(integer,format){
  var text = "";
  for(var i=format.length;i--;){
    if(format[i]=='#'){
      text = (integer%10) + text;
      integer=Math.floor(integer/10);
      if(integer==0){
        return format.substr(0,i).replace(/#(.*#)?/,"")+text;
      }
    }else{
      text = format[i] + text;
    }
  }
  return text;
}
0 голосов
/ 13 июня 2019

Мы можем использовать простую облегченную String.Format библиотеку строковых операций для Typescript.

String.Format ():

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

Формат строки для спецификаторов:

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"

Формат строки для объектов, включая спецификаторы:

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
0 голосов
/ 10 мая 2019

String.prototype.format = function(){
    var final = String(this);
    for(let i=0; i<arguments.length;i++){
        final = final.replace(`%s${i+1}`, arguments[i])
    }
    return final || ''
}

console.log(("hello %s2 how %s3 you %s1").format('hi', 'hello', 'how'));
<h1 id="text">
   
</h1>
0 голосов
/ 24 января 2016

Это не точный дубликат sprintf; однако, он похож и более мощный: https://github.com/anywhichway/stringformatter

Форматные выражения с использованием этой библиотеки принимают форму встроенных объектов Javascript, например,

format("I have {number: {currency: "$", precision:2}}.",50.2); 

вернет "I have $50.20.".

0 голосов
/ 29 сентября 2012

Этот работает с {0}, {1} и {}.

String.prototype.format = function format()
{                                                                                                               
  var msg = this;
  for(var i in arguments)
    msg = msg.replace(/\{\}/,arguments[i]).replace(new RegExp('\\{'+i+'\\}','g'),arguments[i]);
  return msg;
}
...