Languages
[Edit]
EN

JavaScript - insert variable into template text with regular expression

11 points
Created by:
Kenya-Spears
860

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

The article contains 3 approaches:

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

 

1. Simple custom template logic

Edit

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

 

2. String replace based approach

Edit

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

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 it with a variable: function(match, variable) { ... }
  • [0-9a-zA-Z]+ - one or more occurrences of letters or numbers

 

3. Template literals

Edit

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

 

See also

Edit
  1. JavaScript - escape regular expression pattern special characters

References

Edit
  1. String.prototype.replace method - MDN Docs
  2. Regular Expressions - MDN Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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