String.prototype.format

It is proposed that a format method be added to String.prototype that replaces variables in strings, with an option for contextual encoding.

  string.format(values, encoder, open, close, separator)

string is a string the contains variable names which are wrapped in { }. Optionally, the name can include a : followed by an encoding.

  "Page not found: {url:html_text}."

values is either an object or a function. If it is an object, then the {name} is used to retrieve a value from the object. If the result of the retrieval is not undefined, then the variable is replaced with the value. If values is a function, then the {name} is passed to the function as an argument. If the return value is not undefined, then the variable is replaced with the value.

encoder is optional. It is either an object or a function. If it is an object, then the text following the : is used to find a method in the encoder object. The method is passed the translated value that obtain from values. The result is used as the replacement. If encoder is a function, then it is called with the translated value and thetext following the :. The result is used as the replacement.

open is optional. It is a string that identifies the start of a variable. The default is “{”.

close is optional. It is a string that identifies the end of a variable. The default is ‘“}”‘.

separator is optional. It is a string that separates a name from an encoding. The default is “:”.

Douglas Crockford 2010/12/15 20:51

Could you give a usage example? I’m not 100% convinced that I like the behaviour of listing multiple parameters inside a single set of braces. I also think that the format instruction should allow the open/close tokens to be escaped. — Oliver Hunt 2010/12/15 21:11

Is this based on prior art from any popular JS libraries? We should survey what’s out there.

Also, Mike Samuel’s quasis proposal. ES4-era discussion. Python’s solution. — Brendan Eich 2010/12/15 23:31

 
strawman/string_format.txt · Last modified: 2010/12/15 23:38 by brendan
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki