Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"

See Kim's answer below for details.


Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneous replacement instead like in fearphage’s suggestion.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-string-formatting
JavaScript String Formatting - GeeksforGeeks
August 5, 2025 - JavaScript, unlike languages like C# or Python, doesn’t support built-in string formatting using {} placeholders.
Top answer
1 of 16
1662

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"

See Kim's answer below for details.


Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneous replacement instead like in fearphage’s suggestion.

2 of 16
1512

Building on the previously suggested solutions:

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

outputs

ASP is dead, but ASP.NET is alive! ASP {2}


If you prefer not to modify String's prototype:

if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
    });
  };
}

Gives you the much more familiar:

String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

with the same result:

ASP is dead, but ASP.NET is alive! ASP {2}

Discussions

How to format strings in JavaScript like sprintf or String.Format
I’m searching for a JavaScript function that behaves like sprintf() from C/PHP or String.Format() from C#/Java. // A function like this would be perfect let result = formatString("User {0} has {1} points", username, userScore); console.log(result); // "User John has 1500 points" // For number ... More on community.latenode.com
🌐 community.latenode.com
0
May 7, 2025
c# - Use of String.Format in JavaScript? - Stack Overflow
This is driving me nuts. I believe I asked this exact same question, but I can't find it any more (I used Stack Overflow search, Google Search, manually searched my posts, and searched my code... More on stackoverflow.com
🌐 stackoverflow.com
String Interpolation
Why not use the built in feature: const name = 'first name'; const firstName = 'shaniquah'; let output = `my ${name} is ${firstName}`; Also, Doug Crockford made a ‘supplant’ function that operates the way you are describing. More on reddit.com
🌐 r/javascript
7
0
March 15, 2018
Old meme format, timeless JavaScript quirks
Honestly, just using === everywhere will save you a lot of trouble. More on reddit.com
🌐 r/ProgrammerHumor
434
26567
March 13, 2018
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Template_literals
Template literals (Template strings) - JavaScript | MDN
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
🌐
Sentry
sentry.io › sentry answers › javascript › equivalent of printf or string.format in javascript
Equivalent of printf or String.Format in JavaScript | Sentry
October 15, 2023 - In JavaScript, how can I print strings containing the values of variables? I would use printf() to do this in C or PHP and string.Format() to do this in C# or String.format() in Java.
🌐
Latenode
community.latenode.com › other questions › javascript
How to format strings in JavaScript like sprintf or String.Format - JavaScript - Latenode Official Community
May 7, 2025 - I’m searching for a JavaScript function that behaves like sprintf() from C/PHP or String.Format() from C#/Java. // A function like this would be perfect let result = formatString("User {0} has {1} points", username, userScore); console.log(result); // "User John has 1500 points" // For number formatting as well let price = formatNumber(1234.56, "currency"); console.log(price); // "$1,234.56" Currently, I mainly need to format numbers with comma separators for thousands, but having a function ...
🌐
Day.js
day.js.org › docs › en › display › format
Format · Day.js
Get the formatted date according to the string of tokens passed in.
Find elsewhere
🌐
Guru99
guru99.com › home › javascript › javascript string format: methods with examples
JavaScript String Format: Methods with EXAMPLES
July 28, 2025 - For instance, we have now used the “+” operator to concatenate the same variable values, and the “console.log()” method will return a formatted string on the console. ... In your JavaScript program, you can also use the custom function string formatting approach.
🌐
Uio
dhis2-app-course.ifi.uio.no › learn › javascript › data-types › strings › formatting
Formatting - JavaScript String Type : Development in platform ecosystems
Template literals are string literals that allow embedded expressions. These literals can be multi-line and support string interpolation. The embedded expressions can do pretty much anything as long as it's valid JavaScript and they return a value that can be coerced to a string value.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › number › number formatting
Formatting numeric values in JavaScript - 30 seconds of code
February 14, 2024 - When working with currency, it's important to use the appropriate formatting. Luckily, JavaScript's Intl.NumberFormat makes this easy, allowing us to format numbers as currency strings.
🌐
GNU
gnu.org › software › gettext › manual › html_node › javascript_002dformat.html
16.3.7 JavaScript Format Strings
In such a format string, a directive starts with ‘%’ and is finished by a specifier: ‘%’ denotes a literal percent sign, ‘c’ denotes a character, ‘s’ denotes a string, ‘b’, ‘d’, ‘o’, ‘x’, ‘X’ denote an integer, ‘f’ denotes floating-point number, ‘j’ denotes a JSON object.
🌐
npm
npmjs.com › package › string-format
string-format - npm
May 18, 2018 - string-format is a small JavaScript library for formatting strings, based on Python's str.format().
      » npm install string-format
    
Published   May 18, 2018
Version   2.0.0
Author   David Chambers
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Numbers_and_strings
Numbers and strings - JavaScript | MDN
This chapter introduces the two most fundamental data types in JavaScript: numbers and strings. We will introduce their underlying representations, and functions used to work with and perform calculations on them. In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE ...
🌐
freeCodeCamp
freecodecamp.org › news › javascript-string-format-how-to-format-strings-in-js
JavaScript String Format – Formatting Strings in JS
July 11, 2022 - By Dillion Megida JavaScript has many string methods you can use to format strings. In this article, I'll show you some of the most commonly used methods. How to Use the toLowerCase() String Method As the name implies, you use the toLowerCase() strin...
Top answer
1 of 16
74

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>

String.js

// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
    Copyright (c) 2009, CodePlex Foundation
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    *   Redistributions of source code must retain the above copyright notice, this list of conditions
        and the following disclaimer.

    *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
        and the following disclaimer in the documentation and/or other materials provided with the distribution.

    *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
        promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
    IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

    $type = String;
    $type.__typeName = 'String';
    $type.__class = true;

    $prototype = $type.prototype;
    $prototype.endsWith = function String$endsWith(suffix) {
        /// <summary>Determines whether the end of this instance matches the specified string.</summary>
        /// <param name="suffix" type="String">A string to compare to.</param>
        /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
        return (this.substr(this.length - suffix.length) === suffix);
    }

    $prototype.startsWith = function String$startsWith(prefix) {
        /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
        /// <param name="prefix" type="String">The String to compare.</param>
        /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
        return (this.substr(0, prefix.length) === prefix);
    }

    $prototype.trim = function String$trim() {
        /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
        return this.replace(/^\s+|\s+$/g, '');
    }

    $prototype.trimEnd = function String$trimEnd() {
        /// <summary >Removes all trailing white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
        return this.replace(/\s+$/, '');
    }

    $prototype.trimStart = function String$trimStart() {
        /// <summary >Removes all leading white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
        return this.replace(/^\s+/, '');
    }

    $type.format = function String$format(format, args) {
        /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
        /// <param name="format" type="String">A format string.</param>
        /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
        /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
        return String._toFormattedString(false, arguments);
    }

    $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
        var result = '';
        var format = args[0];

        for (var i = 0; ; ) {
            // Find the next opening or closing brace
            var open = format.indexOf('{', i);
            var close = format.indexOf('}', i);
            if ((open < 0) && (close < 0)) {
                // Not found: copy the end of the string and break
                result += format.slice(i);
                break;
            }
            if ((close > 0) && ((close < open) || (open < 0))) {

                if (format.charAt(close + 1) !== '}') {
                    throw new Error('format stringFormatBraceMismatch');
                }

                result += format.slice(i, close + 1);
                i = close + 2;
                continue;
            }

            // Copy the string before the brace
            result += format.slice(i, open);
            i = open + 1;

            // Check for double braces (which display as one and are not arguments)
            if (format.charAt(i) === '{') {
                result += '{';
                i++;
                continue;
            }

            if (close < 0) throw new Error('format stringFormatBraceMismatch');


            // Find the closing brace

            // Get the string between the braces, and split it around the ':' (if any)
            var brace = format.substring(i, close);
            var colonIndex = brace.indexOf(':');
            var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

            if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

            var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

            var arg = args[argNumber];
            if (typeof (arg) === "undefined" || arg === null) {
                arg = '';
            }

            // If it has a toFormattedString method, call it.  Otherwise, call toString()
            if (arg.toFormattedString) {
                result += arg.toFormattedString(argFormat);
            }
            else if (useLocale && arg.localeFormat) {
                result += arg.localeFormat(argFormat);
            }
            else if (arg.format) {
                result += arg.format(argFormat);
            }
            else
                result += arg.toString();

            i = close + 1;
        }

        return result;
    }

})(window);
2 of 16
45

Here is what I use. I have this function defined in a utility file:

  String.format = function() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {       
          var reg = new RegExp("\\{" + i + "\\}", "gm");             
          s = s.replace(reg, arguments[i + 1]);
      }
      return s;
  }

And I call it like so:

var greeting = String.format("Hi, {0}", name);

I do not recall where I found this, but it has been very useful to me. I like it because the syntax is the same as the C# version.

🌐
Taxorubio
taxorubio.com › blog › javascript-fmt
A one-line JavaScript string formatter - Taxo Rubio's blog
August 24, 2025 - You most likely know that JavaScript already has two ways of formatting a string: concatenation and with back-ticked format strings:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › Strings
Handling text — strings in JavaScript - Learn web development | MDN
Since we use quotes to indicate the start and end of strings, how can we include actual quotes in strings? We know that this won't work: ... const goodQuotes1 = 'She said "I think so!"'; const goodQuotes2 = `She said "I'm not going in there!"`; Another option is to escape the problem quotation mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character.
🌐
W3Schools
w3schools.com › js › js_string_templates.asp
JavaScript Template Strings
Template Strings is an ES6 feature. ES6 is fully supported in all modern browsers since June 2017: ... Complete JavaScript String Reference.
🌐
Moment.js
momentjs.com › docs
Moment.js | Docs
Display Format Time from now Time from X Time to now Time to X Calendar Time Difference Unix Timestamp (milliseconds) Unix Timestamp (seconds) Days in Month As Javascript Date As Array As JSON As ISO 8601 String As Object As String Inspect
🌐
Chris Pietschmann
pietschsoft.com › post › 2023 › 09 › 28 › javascript-format-date-to-string
JavaScript: Format Date to String | Chris Pietschmann
September 28, 2023 - Create a Date object: First, create a JavaScript Date object representing the date you want to format. Define a formatting function: Create a function that takes the Date object and formats it according to your desired format. You can do this manually or use a library like date-fns or moment.js for more advanced formatting options. Use the formatting function: Call the formatting function with your Date object as the argument to get the formatted date string.
🌐
W3Schools
w3schools.com › js › js_strings.asp
JavaScript Strings
3 weeks ago - A JavaScript string is zero or more characters written inside quotes.