String.format for javascript
By Anatoly Mironov
sprintf is actually the best javascript implementation of sprintf (string.format). But wait, shouldn’t it be some more .NET-like stuff in SharePoint environment? Indeed there is! (Well, not only in SP, but ASP.NET) String.format(“Hello {0}”, “world”) does exactly the same thing as on server side. Wow, it opens for many opportunities, e.g. in jQuery tmpl: String.format validates arguments, and if all is OK, it invokes another function String._toFormattedString:
function String$\_toFormattedString(useLocale, args) {
var result = '';
var format = args\[0\];
for (var i=0;;) {
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if ((open < 0) && (close < 0)) {
result += format.slice(i);
break;
}
if ((close > 0) && ((close < open) || (open < 0))) {
if (format.charAt(close + 1) !== '}') {
throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);
}
result += format.slice(i, close + 1);
i = close + 2;
continue;
}
result += format.slice(i, open);
i = open + 1;
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}
if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);
var brace = format.substring(i, close);
var colonIndex = brace.indexOf(':');
var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1;
if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid);
var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1);
var arg = args\[argNumber\];
if (typeof(arg) === "undefined" || arg === null) {
arg = '';
}
if (arg.toFormattedString) {
result += arg.toFormattedString(argFormat);
}
else if (useLocale && arg.localeFormat) {
result += arg.localeFormat(argFormat);
}
else if (arg.format) {
result += arg.format(argFormat);
}
else
result += arg.toString();
i = close + 1;
}
return result;
}
```By the way, take a look at summary part of String.format:
/// /// /// ///
Great summary, how could we get intellisense on that in Visual Studio? Anyone know? Another aspect of String.format I have discovered is that unfortunately you cannot format digitals like {0:00} like in C# (e.g. 8 gets 08). Then I recommend you [zlib licensed javascript library called StringFormat from Daniel Mester Pirttijärvi](http://www.masterdata.dyndns.org/r/string_format_for_javascript/).
## Comments from Wordpress.com
####
[javascript: Alert Me on a Page | Bool Tech](http://tech.bool.se/javascript-alert-me-on-a-page/ "") - <time datetime="2013-09-06 15:48:17">Sep 5, 2013</time>
\[…\] ribbon command in OOB SharePoint and let you subscribe to changes on that page. In this code I use String.format which is available on SharePoint pages and \_spPageContextInfo which has existed since SharePoint \[…\]
<hr />