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()]);
}
str.replace(regexp|substr, newSubStr|function)
The first param is the pattern, and the second one is the replacement.
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. |
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 |