65.9K
CodeProject is changing. Read more.
Home

String Formatting in JavaScript

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.57/5 (8 votes)

May 20, 2014

CPOL
viewsIcon

13732

downloadIcon

111

String.Format creates strings from a pattern and values

Introduction

Replaces each format item in a specified string with the text equivalent of a corresponding parameters value. One or more format items in a specified string with the string representation of a specified parameter value.

Syntax

'string with format{0}'.format(Object arg0, Object arg1, Object argn);
Parameters
  • {0}: type of string object
  • arg0: The first object to format
  • arg1: The second object to format
  • argn: The nth object to format

Using the Code

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return args[n];
    });
};

Example

This example shows the use of the string.Format method to combine three strings with formatting options. The format string itself is the first argument to the string.Format method and it is specified as a string literal.

The "{0}", "{1}", "{2}" and "{N}" indicate where the first, second, third and Nth arguments are inserted into the string object. The parameter should be between the { } brackets.

"Hello {0}.{1}, Welcome to our new house at {2}.".format('Mr','Imdadhusen','Ahmedabad');
Output
Hello Mr.Imdadhusen, Welcome to our new house at Ahmedabad.

More Examples

Input
var startDate = "21 APR 2014";
var endDate = "24 APR 2014";
"Your score is {0} out of {1}".format(175,250);
"Dear {0}, Your ticket is booked for {1} days from {2} to {3}. 
Thank you for booking from {4}".format('Imdadhusen',4,startDate, endDate, 'www.happybooking.com');
"World T{0} - {1}th match, Group {2}, {3} v {4}, {3} won by {5} wickets 
(with {6} balls remaining).  {4}'s next match will be on {7}.".format
(20,13,2,'India','Pakistan', 7, 9, '25 Apr 2014');
Ouput
Your score is 175 out of 250 

Dear Imdadhusen, Your ticket is booked for 4 days from 21 APR 2014 to 24 APR 2014. 
Thank you for booking from www.happybooking.com

World T20 - 13th match, Group 2, India v Pakistan, India won by 7 wickets 
(with 9 balls remaining). Pakistan's next match will be on 25 Apr 2014.

Points of Interest

Using the above string utility you can pass n number of parameters with repetitive parameter to generate complete string.

Please feel free to ask me if you would require any help for the same.

Your valuable feedback, comments, suggestions are highly appreciated.