Languages
[Edit]
EN

JavaScript - insert variable into template text with regular expression

8 points
Created by:
Marcin
19550

In JavaScript it is possible to create simple own template logic in following ways.

1. Single variables replace with RegExp class constructor example

// ONLINE-RUNNER:browser;

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

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

function escapeText(text, from, to) {
	var expression = new RegExp(escapeExpression(from), 'g');
	
	return text.replace(expression, to);
}

console.log('BEFORE: \n' + text + '\n');

text = escapeText(text, '{name}', 'John Bean');
text = escapeText(text, '{email}', 'john.bean@dirask.com');
text = escapeText(text, '{age}', '53');

console.log('AFTER: \n' + text + '\n');

2. String replace method example

// ONLINE-RUNNER:browser;

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

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

console.log('BEFORE: \n' + text + '\n');

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

console.log('AFTER: \n' + text + '\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 example

That approach has 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);

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