Using JScript as a batch scripting language (Part II)

Last time, I wrote about synthesizing an #include facility along with handling environment variables in a trivial way.

This time, let’s look at filling in a couple more gaps in JScript’s basic scripting functionality.

What’s wrong with String?

The String class in JavaScript/JScript is … ok. If you work in .NET enough, you’ll eventually get to the point where you’d like a couple of functions that seem to be missing. First, is Trim, which I’ve always thought as obvious:

Scripting.js – String Prototypes
// String Prototypes

String.prototype.Trim = function() { return (this || "").replace(/^\s+|\s+$/g, ""); }

And secondly, is something I miss dearly from when I’m in .NET, is a string Format function. Now, I’ve seen a couple of these that were pretty simple, but I wanted to be able to do some really cool Format strings (and, since the rest of my scripting will rely on them quite a bit, I’m going for the gold here.

Scripting.js – String Prototypes
String.prototype.Format = function() {
    var args = (arguments.length == 1 && typeof (arguments[0]) == "object") ? arguments[0] : arguments;

    result = this;
    while (z = /{(.*?)}/.exec(result))
        try { result = result.replace(z[0], isNaN(z[1]) ? eval(z[1]) : (args[z[1]]||"??<" + z[1] + ">??" )); }
    catch (x) { result = result.replace(z[0], "??<" + z[1] + ">??"); }
    return result.replace("??<", "{").replace(">??", "}");

So, with this tasty little script in my pocket, I can do ad-hoc format strings that use one of a few types of replacement:

// simple parameter # replacement like .NET
var foo = "My Name is {0}. Please to meet you {1}".Format("Garrett", "Mr. Serack");

// *global* variable replacement
ABC = "this is a test";
var bar = "'{ABC}' is really a replacement string".Format();

// really, any legal expression in there is fine.
bar = "'{100+200/75}' is really a replacement value?".Format();

// and if it doesn't match, just leave it alone...
bar = "'{teehee}' isn't really a replacement value.".Format();

// even if it's just a number.
bar = "'{1}' isn't really an index.".Format();

Which spits out the following:

My Name is Garrett. Please to meet you Mr. Serack
'this is a test' is really a replacement string
'102.66666666666667' is really a replacement value?
'{teehee}' isn't really a replacement value.
'{1}' isn't really an index.

Basically, it just looks for anything in braces, and checks to see if it’s a number. if it is, it tries to substitute in the n’th parameter passed in. Otherwise it just does an eval() on it—which, will replace expressions, or global variables. If something goes haywire, it just leaves it alone (well, it does some switcheroo stuff to get past the while loop, but it puts it back in the end).

Next time, we’ll see how to use this… everywhere.

Skip to main content