Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

正则匹配模板字符串 #92

Open
Twlig opened this issue Apr 8, 2022 · 0 comments
Open

正则匹配模板字符串 #92

Twlig opened this issue Apr 8, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Apr 8, 2022

给出模板字符串

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant