Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - insert variable into template text with regular expression

0 contributions
8 points

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. String interpolation example

// 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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more