Explain Codes LogoExplain Codes Logo

Equivalent of String.format in JavaScript / jQuery

javascript
prompt-engineering
functions
polyfills
Alex KataevbyAlex Kataev·Feb 6, 2025
TLDR
// Brace yourself... We're adding a method to the prototype! String.prototype.format = function() { return this.replace(/{(\d+)}/g, (match, number) => // If arguments[number] doesn't exist, keep it as is. typeof arguments[number] != 'undefined' ? arguments[number] : match ); }; // Now behold the fruits of your labor. console.log("Hello {0}, you have {1} unread messages".format("Alice", 12)); // Put on sunglasses 😎: Hello Alice, you have 12 unread messages

This enriches String objects with a format, swapping {0}, {1}, etc. with provided arguments. Alice can rest easy, she knows exactly how many messages she has.

The nitty-gritty details

Developers familiar with ASP.NET AJAX love the String.format function. If you're one of these developers, worry not - you can plate up this method into a more digestible JavaScript or jQuery function!

Looking for startsWith or endsWith functionality? The past is old, but with these prototype functions, you can bring it back:

// Because who starts counting from 1 anyway if (!String.prototype.startsWith) { String.prototype.startsWith = function(search, pos) { return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; }; } // Gets the job done - no frills, no fuss if (!String.prototype.endsWith) { String.prototype.endsWith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; }

The format method from Fast Answer uses replace with a regex to search and swap placeholders. Now, that's elegant! Make sure to handle properly when arguments[number] equates to falsy (like 0 or "").

A .NET flavor in JavaScript

jQuery also dabbles in the String.format art, especially within the jQuery Validation Plugin. Sniff this out:

// Real life example - you're out of coffee ☕ $.validator.format("Your order of {0} has shipped", "coffee"); // Out comes: Your order of coffee has shipped

This works well with form validation. It's part of a bigger framework and has many features for input validation tasks.

Handling curly braces and advanced placeholders

The format function needs a way to handle curly braces {}. This is done by escaping them by doubling them:

// Curly brace lover, this one's for you! String.prototype.format = function() { var args = arguments; return this.replace(/({{)|(}})|{(\d+)}/g, function (m, openBrace, closeBrace, index) { if (openBrace) { return "{"; } if (closeBrace) { return "}"; } return args[index] || ''; }); };

And wait, there's more! You can adjust the logic within the function body for advanced features such as counting placeholders backwards.

Alias and error handling

Modifying global prototypes can haunt you in your dreams if it's not done right. Use an alias:

// Creating a function like Picasso created art! function formatString(str) { var args = Array.prototype.slice.call(arguments, 1); return str.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); } console.log(formatString("Hello {0}, you have {1} unread messages", "Alice", 12)); // Returns: Hello Alice, you have 12 unread messages

Always test thoroughly and check for naming collisions - your alertness today can save your tomorrow!

Expanding horizons

The format pattern can be extended even further to create HTML elements or entire documents based on dynamic data.

JS meets Future

Say hello to JavaScript ES6's template literals, offering dynamic string expressions:

let user = "Alice"; let messages = 12; console.log(`Hello ${user}, you have ${messages} unread messages`);

Legacy Support

Remember, not all environments extend the warm welcome to these updates. Be prepared to use polyfills or alternative methods to support legacy browsers.