与this相关问题,但答案没有解决我的问题。
后端 (Node.js) 从前端 (React) 接收一些 HTML:
// this is merely an example
const price = '<strong>US$ 0.99</strong>';
货币格式取自Number.prototype.toLocaleString()
.看到这个 - $&
?我们稍后会回来讨论。
在下面的代码中,#orderPrice#
将替换为产品的价格 HTML,并且该字符串将通过来自模板的电子邮件发送:
const template = `Your order has a total price of #orderPrice#.`.
const email = template.replace('#orderPrice#', price);
一切都很好,但事实并非如此。如所见here在上述 SO 问题中,$&
在替换字符串时具有特殊含义 - 它插入匹配的字符串,尽管被认为是非标准的。
假设我们有 string1.replace(/pattern/g, string2)
。令我措手不及的是,string1
和 string2
都不能从 $&
位中清除/剥离,所以我什至无法在将价格 html 插入模板之前对其进行清理。我能看到它工作的唯一方法是从一开始就将 $
转义为 $$
,由于使用了 Number.toLocaleString() 这是不可能的
。我们总是可以放弃 .toLocaleString()
并硬编码 US$$
作为解决方法,但这并不能真正解决问题本身。
综上所述,假设我无法在写入时将其转义,我如何清理具有 $&
的字符串?
最佳答案
这个有效:
const email = template.replace('#orderPrice#', () => price);
关于javascript - 如何清理/替换无法转义的 JS 字符串中的 $&(美元 + 符号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67217764/