String Formatting in JavaScript. In javascript, there is no built-in string formatting function.
The equivalent of sprintf("%. 2f", num) in JavaScript seems to be num. toFixed(2) , which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math. round below).
The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.
Here is the format function...
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
And here are the endsWith and startsWith prototype functions...
String.prototype.endsWith = function (suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
String.prototype.startsWith = function(prefix) {
return (this.substr(0, prefix.length) === prefix);
}
This is a faster/simpler (and prototypical) variation of the function that Josh posted:
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
Usage:
'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7)
I use this so much that I aliased it to just f
, but you can also use the more verbose format
. e.g. 'Hello {0}!'.format(name)
Many of the above functions (except Julian Jelfs's) contain the following error:
js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo
Or, for the variants that count backwards from the end of the argument list:
js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo
Here's a correct function. It's a prototypal variant of Julian Jelfs's code, which I made a bit tighter:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};
And here is a slightly more advanced version of the same, which allows you to escape braces by doubling them:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return args[n];
});
};
This works correctly:
js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo
Here is another good implementation by Blair Mitchelmore, with a bunch of nice extra features: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format
Made a format function that takes either a collection or an array as arguments
Usage:
format("i can speak {language} since i was {age}",{language:'javascript',age:10});
format("i can speak {0} since i was {1}",'javascript',10});
Code:
var format = function (str, col) {
col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);
return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return col[n];
});
};
There is an (somewhat) official option: jQuery.validator.format.
Comes with jQuery Validation Plugin 1.6 (at least).
Quite similar to the String.Format
found in .NET.
Edit Fixed broken link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With