如何在nodejs [duplicate]中将json值添加到字符串中

kx1ctssn  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(130)

此问题在此处已有答案

(17个答案)
Processing and replacing text inside double curly braces(2个答案)
Replace keywords from text using javascript [duplicate](1个答案)
Replacing Text Inside of Curley Braces JavaScript(5个答案)
3天前关闭。
我有多个字符串与不同的关键字,如名称,电子邮件和otp.
并且我想将json值动态地嵌入到字符串中,并在json中匹配键。
就像这根绳子。
Dear {user}, Your account for Portal has been created against this Email Address {email}.
和JSON就像这样。
我想把这个json嵌入到字符串中。

{
   "user": "John Wick",
   "email": "some@email.com"
}

我想在字符串中嵌入json后得到这样的结果。
Dear John Wick, Your account for Portal has been created against this Email Address some@email.com.
你知道我怎样才能做到吗?先谢谢你。

2ic8powd

2ic8powd1#

因此,这个示例将遍历JSON的键,并替换任何用大括号括起来的键。

const userDetails = {
   "user": "John Wick",
   "email": "some@email.com"
};

const result = Object.keys(userDetails).reduce((acc, curr) => {
    return acc.replace(`{${curr}}`, userDetails[curr])
}, `Dear {user}, Your account for Portal has been created against this Email Address {email}.`)

console.log(result);

相关问题