String Format with JavaScript

4

Aiming for the String.Format of C #, which is very easy to use, I have searched for something similar to be used in my JavaScript codes.

I found some implementations that are somewhat problematic, so I would like you to have someone who has a succinct and functional code that shares it with our community.

Something that works this way:

String.Format("String {0}.", "format");
//Resultado: "String format"
    
asked by anonymous 27.08.2015 / 14:41

5 answers

5

I found some implementations in the OS. I do not know if any of you get what you want.

One of them is sprintf.js , it seems to be one of the most complete implementations.

Other :

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

Usage:

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
27.08.2015 / 14:47
3

I use replace.

var teste = "Teste {0}";
teste = teste.replace("{0}", "Sucesso");
    
27.08.2015 / 14:46
1

I use this implementation:

if (!String.prototype.format) 
{
    String.prototype.format = function()
    {
        var args = arguments;

        if (typeof args[0] != "object")
        {
            return this.replace(/{\d+}/g, function(m)
            {
                var index = Number(m.replace(/\D/g, ""));
                return (args[index] ? args[index] : m);
            });
        }
        else 
        {
            var obj = args[0],
                keys = Object.keys(obj);

            return this.replace(/{\w+}/g, function(m)
            {
                var key = m.replace(/{|}/g, "");
                return (obj.hasOwnProperty(key) ? obj[key] : m);
            });
        }
    };
}

Uses:

"Test {0} Test {1} Test {2} Test {0}".format("str1", "str2")
  

Test str1 Test str2 Test {2} Test str1 - index 2 not defined

"Test {nome} Test {idade} Test {birth}".format({nome: "str1", idade: 15})
  

Test str1 Test 15 Test {birth} - 'birth' was not defined

    
27.08.2015 / 15:09
1

I know you do not answer your question exactly, but when I need to interpolate variables with javascript text, I use the following method:

var nome = 'João da Silva', idade = 22, nacionalidade = 'Brasileiro';

var string = [
    'Nome: ', nome, '\n'
    'Idade: ', idade, '\n'
    'Nacionalidade: ', nacionalidade].join("");

This code returns:

Nome: João da Silva
Idade: 22
Nacionalidade: Brasileiro

I personally think this code is more readable than the code below:

var string = 'Nome: ' + nome + '\n' +
    'Idade: ' + idade + '\n' +
    'Nacionalidade: ' + nacionalidade;

Furthermore, the difference in performance of using join or + is not something that will impact your page.

    
28.08.2015 / 21:49
0

I use this method in my project:

function format (fmtstr) {
  var args = Array.prototype.slice.call(arguments, 1);
  return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
    return args[index];
  });
}
    
01.09.2015 / 20:25