javascript - 如何清理/替换无法转义的 JS 字符串中的 $&(美元 + 符号)?

标签 javascript node.js replace special-characters currency

this相关问题,但答案没有解决我的问题。

后端 (Node.js) 从前端 (React) 接收一些 HTML:

// this is merely an example
const price = '<strong>US$&nbsp;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)。令我措手不及的是,string1string2 都不能从 $& 位中清除/剥离,所以我什至无法在将价格 html 插入模板之前对其进行清理。我能看到它工作的唯一方法是从一开始就将 $ 转义为 $$ ,由于使用了 Number.toLocaleString() 这是不可能的。我们总是可以放弃 .toLocaleString() 并硬编码 US$$ 作为解决方法,但这并不能真正解决问题本身。

综上所述,假设我无法在写入时将其转义,我如何清理具有 $& 的字符串?

最佳答案

这个有效:

const email = template.replace('#orderPrice#', () => price); 

关于javascript - 如何清理/替换无法转义的 JS 字符串中的 $&(美元 + 符号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67217764/

相关文章:

node.js - 值没有被插入到 PostgreSQL 数据库中

node.js - 在heroku上部署 Node 服务器并收到 "SyntaxError: Unexpected token import"

c++ - 尽管参数正确,但简单的字符串替换给出错误

javascript - 真正的弱引用事件发射器/调度器 : is it possible?

javascript - 将变量传递给 componentDidMount

javascript - Highcharts 3 之类的菜单按钮不会显示

javascript - 如果没有 child ,则针对特定元素

javascript - 无法在 Handlebars 中使用 if 条件

javascript - 如何解析字符串

python - 从字符串中删除多个单词的更好方法?