JavaScript String.format

AleMonteiro 2 Tallied Votes 397 Views Share

Hi all. This is somewhat the equivalent of .NET String.Format(String, Args);

Usages:

'Hello {0}'.format('DaniWeb!');

String.format('{0} {1} {2}', 'Hi', 'Again', 'Good Fella');

String.format('Hello {prefix} {name}', { prefix: 'Sr.', name: 'HeyHeyHey'});

I know there's lots of String.formats out there(some simpler and some more complex), but this is the one i've been using for the past years and it works really well for me.

Remarks: I didn't write this from scratch, couple years ago I put together a couple of simpler sinnepts to make this one. But I couldn't find the sources to give the deserved credits.

Hope it may be helpful.

Cheers!

JorgeM commented: very nice! +12
if ( !('format' in String.prototype)) {
	
	String.prototype.format = function () {
		return String.format(this, arguments.length == 1 ? arguments[0] : arguments);
	};

	String.format = function (source, params) {
		var _toString = function (obj, format) {
			var ctor = function (o) {
				if (typeof o == 'number')
					return Number;
				else if (typeof o == 'boolean')
					return Boolean;
				else if (typeof o == 'string')
					return String;
				else
					return o.constructor;
			} (obj);
			var proto = ctor.prototype;
			var formatter = typeof obj != 'string' ? proto ? proto.format || proto.toString : obj.format || obj.toString : obj.toString;
			if (formatter)
				if (typeof format == 'undefined' || format == "")
					return formatter.call(obj);
				else
					return formatter.call(obj, format);
			else
				return "";
		};
		if (arguments.length == 1)
			return function () {
				return String.format.apply(null, [source].concat(Array.prototype.slice.call(arguments, 0)));
			};
		if (arguments.length == 2 && typeof params != 'object' && typeof params != 'array')
			params = [params];
		if (arguments.length > 2)
			params = Array.prototype.slice.call(arguments, 1);
		source = source.replace(/\{\{|\}\}|\{([^}: ]+?)(?::([^}]*?))?\}/g, function (match, num, format) {
			if (match == "{{") return "{";
			if (match == "}}") return "}";
			if (typeof params[num] != 'undefined' && params[num] !== null) {
				return _toString(params[num], format);
			} else {
				return "";
			}
		});
		return source;
	};
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.