Template String Replacement Function


Today’s article introduces an efficient method for replacing template values in a JavaScript string. Although, concatenating strings together is the default way that JavaScript programmers insert values into a string, using a replacement function can lead to more readable code. Additionally, the replacement function is fast enough that it rarely affects performance.

Getting ready

In the following example, several values are concatenated into a string:

var http = "https:" == document.location.protocol ? "https" : "http";
var domain = "www.mattsnider.com";
var page = "text.php";
var url = http + "://" + domain + "/" + page + "?param=" + 123;

This works, but the url variable isn’t the most readable string. A more developer friendly way to handle the variable would be to use template values and a replacement function:

var url = "{0}://{1}/{2}?param={3}";

This url is more readable, but now we need a function that injects values into the string.

How do it…

To inject values into a string we use the replace function of the String with a regular expression matching the template values ({#}) and a callback function. Here is the injection function:

function string_inject(sSource, aValues) {
	var i = 0;

	if (aValues && aValues.length) {
		return sSource.replace(/\{\d+\}/g, function(substr) {
			var sValue = aValues[i];

			if (sValue) {
				i += 1;
				return sValue;
			}
			else {
				return substr;
			}
		})
	}

	return sSource;
};

To use this function, pass a template string as the first argument and an array of values as the second:

string_inject(url, [http, domain, page, 123]);

How it works…

The native string replace function can optionally accept a function as its second argument (see documentation for more info). When a function is provided, it will execute that function on each value found by the regular expression (the first argument). The first value of the callback function is the matched substring, and all we need to use for this code snippet, and the value returned will be used to replace the matched substring. In this example, the array of values are iterated on and the values from the array are returned in the order that they appear in the array. If the array is too short, then the matched template substring is returned.

I mostly use this method when I have HTML templates stored in JavaScript that need to have values replaced. I’m sure you’ll find your own uses.

There’s more…

Because the callback function simply iterates over the values in the value array, as each┬áregular expression match is found, the function doesn’t actually care about the number ({#}) that triggered the match. It will simply replace the first match with the first value, second with the second value, etcetera. For most situations this is enough, but if you care about order, you might change the callback to the following:

function(substr) {
	var i = parseInt(substr.replace(/\{|\}/g, ), 10);
	var sValue = aValues[i];

	if (sValue) {
		return sValue;
	}
	else {
		return substr;
	}
}

This version of the callback parses the array index from the matched substring value, so {1} matches the value as position 1 in the array no matter where is appears in the string.