June 15, 2009

Sprint for JavaScript

usage: “Inside a string id\n or \n “ (where id is (optional) token from table below, and n is the argument position to substitute.

	"":	String (default)
"$": String
"#": Number
"%": Integer
"!": Boolean
"_": Char from charCode
"@": Locale version

javascript code:

function sprint(str){var S=String,A=arguments,c=S.fromCharCode,T={ "": S, "$": S, "#": Number, "%": parseInt, "!": Boolean, "_": function(n){return c(parseInt(n,10));}, "@": function(V){return V.toLocaleString ? V.toLocaleString() : S(V); } }; return S(str).replace(/([@#%$!_]?)([\x00-\x08])/g, function(a,t,p){return T[t||""](A[p.charCodeAt(0)],10); }); }//end sprint()

examples:

sprint(  "Hello $\1. You are %\2 years old \1."  , "dan", 123 );
//==”Hello dan. You are 123 years old dan.”
sprint("Number(#):#\1, Integer(%):%\1, Char(_):_\1, \
String($):$\1, Boolean(!):!\1,  Local(@):@\1,  default:\1 "  , 1234.5678 );
//==
Number(#):1234.5678, 
Integer(%):1234, 
Char(_):Ӓ, 
String($):1234.5678, 
Boolean(!):true,  
Local(@):1,234.5678,  
default:1234.5678