题目很简单:实现一个render方法,完成下述功能:
const year = '2020'
const month = '03'
const 'day' = '17'
const str = render('${year}-${month}-${day}')({year, month, day})
console.log(str)
// 输出:2020-03-17
大概看一下题目,发现两个考点,一个是函数柯里化,一个就是字符串替换操作。说到字符串替换,那自然就会想到正则表达式。
str.replace(reg, function)
利用字符串的replace
方法,加上正则表达式的捕获组,我们可以捕获到到 `${year}`这样的字符串,并把它替换成我们想要的内容。话不多说来看下代码:
const render = (format) => {
return (map) => {
return format.replace(/\$\{(year|month|day)\}/g, function (str,key) {
return map[key]
})
}
}
console.log(render('${year}-${month}-${day}')({year: '2020', month: '03', day: '17'}))
// 2020-03-17
更多面试知识,欢迎关注我的个人微信公众号:编程男孩