【问题标题】:How to sanitize/replace $& (dollar + ampersand) in a JS string that cannot be escaped?如何清理/替换无法转义的 JS 字符串中的 $&(美元 + 符号)?
【发布时间】:2021-07-16 22:36:44
【问题描述】:

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

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

// this is merely an example
const price = '<strong>US$&nbsp;0.99</strong>';

货币格式取自Number.prototype.toLocaleString()。看到这一点 - $&amp;?我们稍后再讨论。

在下面的代码中,#orderPrice# 将被替换为产品的价格 HTML,字符串将通过来自模板的电子邮件发送:

const template = `Your order has a total price of #orderPrice#.`.

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

一切都很好,花花公子,但事实并非如此。正如 here 和上述 SO 问题中所见,$&amp; 在替换字符串时具有特殊含义 - 尽管被认为是非标准的,但它会插入匹配的字符串。

假设我们有string1.replace(/pattern/g, string2)。让我措手不及的是 string1string2 都不能被清理/剥离 $&amp; 位,所以我什至无法在将价格 html 插入模板之前对其进行清理.我可以看到它工作的唯一方法是从一开始就将$ 转义为$$,由于使用Number.toLocaleString(),这是不可能的。我们总是可以放弃.toLocaleString() 和硬编码US$$ 作为一种解决方法,但这并不能真正解决问题本身。

说了这么多,假设我在写入时无法逃脱它,我该如何清理具有$&amp; 的字符串?

【问题讨论】:

    标签: javascript node.js replace special-characters currency


    【解决方案1】:

    这行得通:

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

    【讨论】:

      【解决方案2】:

      您需要将price 中的任何$ 字符加倍。

      const price = '<strong>US$&nbsp;0.99</strong>';
      const template = `Your order has a total price of #orderPrice#.`;
      const email = template.replace('#orderPrice#', price.replace(/\$/g, '$$$$'));
      console.log(email);

      【讨论】:

      • 另一个选项是const email = template.replace('#orderPrice#', () =&gt; price);
      • 感谢两位的回复。 @thorn0,您可以发表您的评论作为答案吗?两种解决方案都有效,但你的更优雅一点,这是我选择的。
      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 2021-08-21
      • 2021-04-25
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 2015-08-21
      相关资源
      最近更新 更多