The Problem
var greeting = 'My name is ${name}, age ${age}, I am a ${job.jobLevel} ${job.jobName}.';
var employee = {
name: 'XiaoMing',
age: 11,
job: {
jobName: 'designer',
jobLevel: 'senior'
}
}
var result = greeting.render(employee);
console.log(result); // My name is XiaoMing, age 11, I am a senior designer.
The solution
This is my solution:
// my solution
String.prototype.render = function (options) {
return this.replace(/(?:\$\{)([\.\w]+)(?:\})/g, (match, $1) => {
if ($1.includes('.')) {
var p = $1.split('.');
return p.reduce((p, n) => p[n], options);
}
return options[$1];
})
}
And the other one:
String.prototype.render = function (options) {
with(options) {
return eval('`' + this + '`')
}
}
Tips:
This is my first article, so, be kind with me.
If you see some improvement that can be made, please, let me know in the comments.
If you liked this article, please, motivate-me in the comments.
Thank you for reading ❤️ !
Top comments (0)