CHUVASH.eu

CHunky Universe of Vigouros Astonishing SHarepoint :)

String.format for javascript

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:

/// <summary locid="M:J#String.format" />
/// <param name="format" type="String"></param>
/// <param name="args" parameterArray="true" mayBeNull="true"></param>
/// <returns type="String"></returns>

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.

About these ads

One response to “String.format for javascript

  1. Pingback: javascript: Alert Me on a Page | Bool Tech

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Discovering SharePoint

And having fun doing it

Bram de Jager's SharePoint blog

My view and thoughts on SharePoint.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

The Zuul Cat Idea Brewery

Where ideas on software development and entrepreneurship brew.

Paul J. Swider

Inspire! Teach! Awe!

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Alexander Ahrens

MCPD | SharePoint | Web Development | JavaScript | .NET

Cameron Dwyer | SharePoint, Outlook, OnePlaceMail

OnePlaceMail, SharePoint, Outlook & Life's Other Little Wonders

.:paul.tavares:.

Me and My doings!

Share SharePoint Points

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan.com

Ryan Dennis is a SharePoint Solutions Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

Follow

Get every new post delivered to your Inbox.

Join 245 other followers

%d bloggers like this: