Languages
[Edit]
EN

JavaScript - insert variable into template text with regular expression

11 points
Created by:
Kenya-Spears
530

In this article, we want to show how in simple way, use string templates in JavaScript.

The article contains 3 aproaches:

  • simple custom template logic,
  • string replace based approach,
  • templates literals (provided by modern JavaScript).

 

1. Simple custom template logic

This solution finds matching variables in the text and replace them with desired values. Variables in the text are marked with curly brackets (e.g. {variable_name_here}).

// ONLINE-RUNNER:browser;

function escapePattern(text) {
	return text.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}

function renderVariable(text, name, value) {
  	var pattern = escapePattern(name);
	var expression = new RegExp('{' + pattern + '}', 'g');
	return text.replace(expression, value);
}

function renderText(text, variables) {
	var result = text;
  	for (var i = 0; i < variables.length; ++i) {
      	var variable = variables[i];
    	result = renderVariable(result, variable.name, variable.value);
    }
  	return result;
}


// Usage example:

var text = 
	'This is {name} profile.\n' + 
	'Details:\n' +
	'  name: {name}\n' +
	'  email: {email}\n' +
	'  age: {age}\n' +
	'Contact with {name} by {email}.';

var variables = [
  	{name: 'name',  value: 'John Bean'           },
    {name: 'email', value: 'john.bean@dirask.com'},
    {name: 'age',   value: '53'                  }
];

var renderedText = renderText(text, variables);

console.log('-- BEFORE --\n' + text + '\n\n');
console.log('-- AFTER --\n' + renderedText + '\n\n');

2. String replace based approach

This solution just replaces variables in the text using function logic.

// ONLINE-RUNNER:browser;

function renderText(text, variables) {
  	return text.replace(/\{([0-9a-zA-Z_-]+)\}/g, function(match, variable) {
		return variables[variable];
	});
}


// Usage example:

var text = 
	'This is {name} profile.\n' + 
	'Details:\n' +
	'  name: {name}\n' +
	'  email: {email}\n' +
	'  age: {age}\n' +
	'Contact with {name} by {email}.';

var variables = {
	name : 'John Bean',
	email : 'john.bean@dirask.com',
	age : '53'
};

var renderedText = renderText(text, variables);

console.log('-- BEFORE --\n' + text + '\n\n');
console.log('-- AFTER --\n' + renderedText + '\n\n');

To find matches /\{([0-9a-zA-Z]+)\}/g expression has been used. 
Where:

  • /.../g - regular expression with global searching (all occurrences)
  • \{...\} - matches only text bounded with { }
  • (...) - group content and replace with variable: function(match, variable) { ... }
  • [0-9a-zA-Z]+ - one or more occurrences of letters or numbers

3. Template literals

That approach has a second name like Template strings too. In other languages, we can find substitute names like Expression interpolation or String interpolation.

// ONLINE-RUNNER:browser;

var name = 'John Bean';
var email = 'john.bean@dirask.com';
var age = 53;

var text = 
	`This is ${name} profile.
Details:
  name: ${name}
  email: ${email}
  age: ${age}
Contact with ${name} by ${email}.`;

console.log(text);

See also

  1. JavaScript - escape regular expression pattern special characters

References

  1. String.prototype.replace method - MDN Docs
  2. Regular Expressions - MDN Docs
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join