JavaScript string formatting inspred by Python’s String.format()
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
LICENSE.markdown
README.markdown

README.markdown

JavaScript String.format()

JavaScript String.format() brings Python-inspired string formatting to JavaScript. Now you can stop concatenating strings with the + operator like a caveman.

Update - January 27, 2015:

I have moved JavaScript String.format() into my JavaScript-Utils project. The version in this repository will not be maintained.

Usage:

  1. Include src/javascript-string-format.js in your HTML document:

     <script type="text/javascript" src="<path-to-javascript-resources>/javascript-string-format/src/javascript-string-format.js"></script>
    
  2. Insert format arguments enclosed in curly braces in a string:

     var string = 'Hello, my name is {firstname} {lastname}.';
    
  3. Call .format() on the string, passing in an object containing the format arguments and replacement values:

     var string = 'Hello, my name is {firstname} {lastname}.';
     var formattedString = string.format({
     	firstname: 'Tony',
     	lastname: 'Wallace'
     });
    
     console.log(formattedString); // 'Hello, my name is Tony Wallace.'
    
  4. .format() also works on a string literal:

     var formattedString = 'Hello, my name is {firstname} {lastname}.'.format({
     	firstname: 'Tony',
     	lastname: 'Wallace'
     });
    
     console.log(formattedString); // 'Hello, my name is Tony Wallace.'
    
  5. Format arguments may be reused. You can also insert whitespace between the arguments and curly braces:

     var formattedString = 'My first name is { firstname }. My last name is { lastname }. My full name is { firstname } { lastname }.'.format({
     	firstname: 'Tony',
     	lastname: 'Wallace'
     });
    
     console.log(formattedString); // 'My first name is Tony. My last name is Wallace. My full name is Tony Wallace.'
    

License:

JavaScript String.format() is made available under the MIT License. See LICENSE.markdown for details.

Credits:

JavaScript String.format() was created by Tony Wallace.