Skip to content

Instantly share code, notes, and snippets.

@ivanberry
Last active March 8, 2018 09:25
Show Gist options
  • Save ivanberry/a16b21861d25e3e88a6c9044903c4020 to your computer and use it in GitHub Desktop.
Save ivanberry/a16b21861d25e3e88a6c9044903c4020 to your computer and use it in GitHub Desktop.
Basic template render function

Make a basic template render function

Given:

var str = '{{name}}is cool, and he is only {{age}} years old!';
var context = {
  name: 'ivanberry',
  age: 20
}
render(str,content); //output ivanberry is cool, and he is only 20 years old;
function render(str, context) {
  return str.replace(/{{(.*?)}}/g, (match, value) => context[value.trim()]);
}

string.prototype.replace

str.replace(regexp|substr, newSubStr|function)

The first param is the pattern, and the second one is the replacement.

Return Value

new string with some or all patterns replaced by a replacement.

Pattern Inserts
$$ Inserts a '$'
$& Inserts the matched substring
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed.

Formal params of function as replacement

Possible name Supplied value
match The matched substring
p1,p2... The nth parenthesized submatch string, provided the first argument to replace was a RegExp object. For example, if /(a+)
offest The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
string The whole string being examed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment