slight ot: python like string interpolation with j*script

Mark McEahern mark at mceahern.com
Mon Apr 15 15:04:41 EDT 2002


Hi, I was messing around with JScript this weekend and found myself missing
Python.  One of the many things I missed was string formatting.  You know:

  s = "The expected string %s did not match the generated string %s."
  print s % (expected, generated)

That sort of thing.

I got to wondering, could you do that with JScript?  I figured maybe I
wasn't reading the docs closely enough.  Well, it turns out that there's no
native support for it in JScript, but you can get something quite close with
regular expressions.  I'd be interested in any feedback on the following
from fellow Pythonistas, especially those who sometimes dabble in JScript.

Cheers,

// mark

<%@ LANGUAGE="JScript" %>
/*
** Written to be run from a ASP web page, but it wouldn't be too hard to
extract
** this for running it, say, in a WScript environment or client-side
JavaScript.
*/

<%

function debugWrite(s)
{
  Response.Write("<p>" + s + "</p>")
}

// Who needs Scripting.Dictionary, when this is such a piece of cake?
dict = new Object()
dict.expected = "foo"
dict.generated = "bar"

// Build this functionality into String, why don't ya?
String.prototype.formatWith = function(dict)
{
  var re = /\$(\w+)/gi
  var results
  var temp = new String(this.valueOf())
  while((results = re.exec(this)) != null)
  {
    temp = temp.replace(results[0], dict[results[1]])
  }
  return temp
}

s = "The $expected string does not match the $generated string."
t = s.formatWith(dict)
debugWrite(t)

%>






More information about the Python-list mailing list