[Solved-5 Solutions] Javascript equivalent to printf.format - javascript Tutorial



Problem:

JavaScript equivalent to printf/String.Format

Solution 1:

Try sprintf() for JavaScript. If we want to do a simple format method on our own, don’t do the replacements successively but do them simultaneously.
Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally we would expect the output to be {1}{0} but the actual output is {1}{1}

Solution 2:

// First, checks if it isn't implemented yet.
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
      ;
    });
  };
}
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
Outputs

ASP is dead, but ASP.NET is alive! ASP {2}

If we prefer not to modify String's prototype:

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

Gives you familiar:

String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
with the same result:

ASP is dead, but ASP.NET is alive! ASP {2}

Solution 3:

"Hello, {name}, are we feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});
Javascript equivalent to printf format

Learn javascript - javascript tutorial -js- javascript examples - javascript programs

We get this output:

Hello, Gabriel, are we feeling OK?

We can use objects, arrays, and strings as arguments! we got its code and reworked it to produce a new version of String.prototype.format:

String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
    "use strict";
    var str = this.toString();
    if (arguments.length) {
        var t = typeof arguments[0];
        var key;
        var args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];

        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }

    return str;
};

Note the clever Array.prototype.slice.call(arguments) call -- that means if we throw in arguments that are strings or numbers, not a single JSON-style object, we get C#'s String.Formatbehavior almost exactly.

"a{0}bcd{1}ef".formatUnicorn("foo", "bar"); // yields "aFOObcdBARef"

Because Array's slice will force whatever's in arguments into an Array, whether it was originally or not, and the key will be the index (0, 1, 2...) of each array element coerced into a string (eg, "0", so "\\{0\\}" for our first regexp pattern).

Read Also

Java Strings

Solution 4:

You can use this:

String.prototype.format = function() {
    var formatted = this;
    for (var we = 0; we < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

With this option we can replace strings like these:

'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');

With our code the second {0} wouldn't be replaced.

Solution 5:

From ES6 on we 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.


Related Searches to javascript tutorial - Javascript equivalent to printf.format