Twlig / issuesBlog

MIT License
3 stars 0 forks source link

正则匹配模板字符串 #92

Open Twlig opened 2 years ago

Twlig commented 2 years ago

给出模板字符串

var str = 'my name is ${name}, and I am ${age}''

现在有一个对象

var obj = {
    name: 'zzy',
    age: 23
}

需要用obj中的对象替换模板字符串中的数字

function parseStr(str, obj) {
    Object.keys(obj).forEach(key => {
        str = str.replace(new RegExp(`\\$\{${key}\}`, 'g'), obj[key])
    })
    return str
}
parseStr(str, obj)
//my name is zzy, and I am 23