Fog Creek Software
Discussion Board




Javascript formatted output

As aussie chick was reminded, this used to be a technical question.  So, is there a simple way to do formatted output in javascript?  I'm running outside of a web browser, on WinXP.  Invocation is "cscript foo.js", or double clicking on the foo.js icon.

What I want to do is pretty much C's printf:
printf("%2d lines in file %16s, CRC 0x%08x\n", line, name, crc);

I have access to FileSystemObject and all it's properties, methods, and whatnot, as well as the other stuff that's attached to a "WinXP Programming Environment".

Snotnose
Thursday, June 10, 2004

"This used to be a technical question".  Sigh.  I'm an idiot.  Spelling and grammar are lossed arts :(

"".replace(/question/forum/);

Snotnose
Thursday, June 10, 2004

"".replace(/lossed/lost/);

.
Thursday, June 10, 2004

"".replace(/$/ \\subtle/)

Snotnose
Thursday, June 10, 2004

uhh.. wouldn't that just append the string "\subtle" at the end of the subject string?  I don't get it.

muppet is now from madebymonkeys.net
Thursday, June 10, 2004

This may not help a bit, but I have seen printf "ported" to Java.

http://sharkysoft.com/archive/printf/docs/javadocs/lava/clib/stdio/doc-files/introduction.htm

The guy who did it has the specs of how he did it. I would think that you could either make a Javascript call to the Java component (if you can get it) or roll your own using the spec.

CF
Thursday, June 10, 2004

Well, if nobody has any suggestions then the following works for me.  Hope my code formatting doesn't go into the weeds.

----------
function FormatDatum(datum, width)
{
  var limit = width < 0 ? -width : width;

  for(var padding = "                        "; padding.length < limit; )
      padding += padding;

  var str, result;
  if(typeof datum == "number")
      str = String(datum);
  else if(typeof datum == "string")
      str = datum;
  else
      return datum;        // Add your own types if you care.

  if(str.length >= limit)
      result = str;
  else if(width >= 0) {
      result = str + padding;
      result = result.slice(0, limit);
  } else
  {
      result = padding + str;
      result = result.slice(result.length - limit, result.length);
  }
  return result;
}

var data = new Array(
  "foo", 8,
  "really really freaking unbelievably long foo", 8,
  0, 3,
  12, 3,
  12345, 3
);

for(var i = 0; i < data.length; i += 2)  {
  WScript.Echo(FormatDatum(data[i], data[i + 1]));
  WScript.Echo(FormatDatum(data[i], -data[i + 1]));
}

------------------------

Snotnose
Thursday, June 10, 2004

This is not my joel-on-software day.  Change the line "else if(width >= 0) {" to "else if(width < 0) {".

Snotnose
Thursday, June 10, 2004

*  Recent Topics

*  Fog Creek Home