String Format with Javascript

Asked

Viewed 14,101 times

7

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

I found some rather problematic implementations, aiming at this, I would like that if someone has a succinct and functional code, that share it with our community.

Something that works that way:

String.Format("String {0}.", "format");
//Resultado: "String format"
  • 1
  • Was that I only floated, I did not understand what you want to do, and looking at the answers there yes I was sure that I did not understand anything.. rsrsrsr

  • As such @Sneepsninja rs .. is that in c# has this estring format above which is very practical .. to concatenate text in the middle of the string.. ai was looking for a similar implementation. Get it ? : D

  • Bro, if you think I didn’t get it... would you just concatenate like "string" + "other" ? I guess I didn’t get it because I don’t know anything about c#

6 answers

7


I found some implementations in the OS. I don’t know if any answer what you want.

One of them is the sprintf.js, 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
            ;
        });
    };
}

I put in the Github for future reference.

Use:

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
  • Exactly what I needed. : ) thanks

  • 2

    I have always heard that it is not good practice to extend the javascript native objects, so I did a quick search to find the reasons. One of them is that if the javascript string gains a function format() official, there is a chance that your scripts will break. I would choose to make a new class, like Str.format("{0} is dead, but {1} is alive! {0} {2}", "ASP", "ASP.NET") or something like that. Anyway, cool you check if format() already exists before extending.

  • It has the same risk, low, but it has. Then each one sees how much he wants to take the risk and to facilitate.

6

I use the replace.

var teste = "Teste {0}";
teste = teste.replace("{0}", "Sucesso");
  • 1

    +1 for this answer by using pure Javascript. We often seek more complicated solutions than necessary.

5

From ES6 you can use this template:

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

Link to the detailed reply

2

I know it doesn’t exactly answer your question, 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

Personally, I think that code is more readable than the code below:

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

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

  • you can use \n\ to make a multi-line string... multi-line

  • 1

    True @Tobymosque, you can escape the line break with the backslash, but it is not considered good practice because of the ease of making mistakes, since javascript interprets line break as end of expression. Take a look at this answer: http://stackoverflow.com/a/13808106/83284

2

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);
            });
        }
    };
}

Usages:

"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' has not been defined

0

I use this one 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];
  });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.