équivalant à printf/String. Format

Mots clés : javascriptprintfstring.formatjavascript

meilleur 5 Réponses équivalant à printf/String. Format

vote vote

95

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

88

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

75

"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"}); 
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; }; 
"a{0}bcd{1}ef".formatUnicorn("FOO", "BAR"); // yields "aFOObcdBARef" 
vote vote

70

(12.345).toFixed(2); // returns "12.35" (rounding!) (12.3).toFixed(2); // returns "12.30" (zero padding) 
(33333).toExponential(2); // "3.33e+4" 
(3735928559).toString(16); // to base 16: "deadbeef" parseInt("deadbeef", 16); // from base 16: 3735928559 
vote vote

58

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

Questions similaires