Notice This is a beta feature offered by Google. Also this is automatic translation, which means the results are often inacurate and/or hilarious. Enjoy.

ARCHIVES / RSS
Blog

jQuery: Advanced String Formatting à la Python3K

h3  ~  17 May 2008, 17:00  –  2 comments

This week in my spare time I implemented the Python3000 Advanced String Formatting described here.

It was more easy than I apprehended, less than 200 lines (without comments) and I managed to use a minimal amount of regular expressions so it's quite fast. Still, I did this as a hobby and it's the first release so don't expect it to be perfect, I don't recommend to use it in serious projects yet. That said, comments, feedback and patches are more than welcome.

You can submit bugs to the issues tracker on the project page, please specify the plugin (jquery-string) in labels.

The API documentation is here.

Usage examples

Simple replacement

// all return "1bc"
$.format('{a}bc', {a:'1'}) // named arguments
$.format('{0}bc', [1])     // array arguments
$.format('{0}bc', 1)       // normal arguments

Type conversion

$.format('{a:d}bc', {a:'a1'})  // return "1bc"

$.format('{a:d}bc', {a:1.5})   // return "1bc"

$.format('{a:.2f}bc', {a:'1'}) // returns 1.00bc

Padding

$.format('{a:08.2f}bc', {a:'1'}) // return 00001.00bc

User defined formatting

$.extend(jQuery.strConversion, 
    {'U': function(input, arg){ return input.toUpperCase(); }
});

$.format('{0:U}bc', 'a') // return Abc

Known differences with Python

  • JavaScript precision is more limited than Python
  • Python zero pad exponent (10 -> 1.0e+01), not JavaScript? (10 -> 1.0e+1)
  • My repr and str implementation is not like Python

To come

  • -|+|s flags handling
  • proper escaping
  • repr should truncate using precision
  • jQuery.fn extension, ex: $('input').format('0.2f')
  • sprintf method using the same conversion object, because sprintf is also useful

post a comment Comments

I like it.

DomesticMouse ~ May 17, 2008 at 8:39 p.m.

Does it work on Internet Explorer 4 on my cell phone?

Stupid McRetard ~ May 18, 2008 at 8:46 p.m.
Copyrighted stuff .. u know.