Pretty useful jQuery function I’ve called “formatVarString”. Its takes a string as the first argument with n arguments after with which to perform variable substitution (returning variables as part of a string using parenthesis).

You can simply use {1}, {2}, {3} etc to reference variables in a string.


formatVarString('we love {1}.', 'jQuery4u');
//output: "we love jQuery4u."

formatVarString('{1} is a {2} aimed to help you learn {3}.', 'jQuery4u', 'blog', 'jQuery');
//output: "jQuery4u is a blog aimed to help you learn jQuery."

The jQuery Format Function

var JQUERY4U = {};
formatVarString: function()
		var args = [];
		if(this.toString() != '[object Object]')

		var pattern = new RegExp('{([1-' + args.length + '])}','g');
		return String(args[0]).replace(pattern, function(match, index) { return args[index]; });
JQUERY4U.UTIL.formatVarString('{1} is a {2} aimed to help you learn {3}.', 'jQuery4u', 'blog', 'jQuery');
//output: "jQuery4u is a blog aimed to help you learn jQuery."
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.