Craig Gibbons' Lifeblog lifeblog://tri.eat.net

7Jan/050

An implementation of string.Format() in JScript

Once you start using string.Format() you can't imagine how you ever lived without it. The concept is extremely simple, take a string, use some tokens and pass some values. The tokens are then replaced with the values in the order passed. In C#, a good example of this would be building a URL:

string queryStringParameterName = "index";
int pageIndex = 0;
string URL = string.Format("~/Secure/Default.aspx?{0}={1}", queryStringParameterName, pageIndex);

The example above is a little trivial, but it really is a powerful tool and one which every language absolutely needs. One of my other great loves is JScript. Despite it's limitations, it really is a great little language with many advanced features that the casual user never learns about, but JScript can do pretty much anything, which is probably the reason Microsoft made it one of the default .NET languages along with C# and VB.Net. Of course, JScript.NET is only intended for use server side so I wrote this little JScript function for the client side.

function stringFormat(s) {
 try {
  var argLen = arguments.length;

  for(var i = 1; i < argLen; i++) {
   var replaceToken = "{" + (i - 1) + "}";

   if(s.indexOf(replaceToken) != -1) {
    s = s.replace(replaceToken, arguments[i]);
   } else {
    throw new Error(6000, "At least one of the parameters passed was incorrect.");
   }
  }

  alert(s);
 } catch(e) {
  alert(e.description);
 }
}

You can call this function using the folowing code, run out of a button click here just for simplicity sake:

<INPUT onclick="stringFormat('This {0} a {1}', 'is', 'test')" type=button value="Click me" name=click>

Happy coding!

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.