javascript - String.replace 的转义 $ 符号

标签 javascript regex

在下面的 String.replace 行中,lossLocation.state$ ,

替换后$符号被删除,

我需要保留 $,因为它在变量中使用。

 '{0}'.replace(
         '{0}'
       , 'categories.Country === \'$formData.lossLocation.state$\'.toUpperCase()')

它给了我

"categories.Country === '$formData.lossLocation.state'.toUpperCase()"

预期结果应该是

"categories.Country === '$formData.lossLocation.state$'.toUpperCase()"

我已经尝试了以下方法,但在替换时仍然被删除

state\$

最佳答案

正如 String.prototype.replace() 中所述。要在替换内容中转义“$”,您应该使用“$$”而不是“\$”。

因此构建它的正确方法是

'{0}'.replace('{0}', 
    'categories.Country === \'$formData.lossLocation.state$\'.toUpperCase()'
        .replace(/\$/g, '$$$$')
)

关于javascript - String.replace 的转义 $ 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985734/

相关文章:

javascript - 休息 API : how to pass the JSONresponse to Javascript?

javascript - fetch 原生支持多文件上传吗?

javascript - 使用唯一的 IDS 将相同的按钮 UI 图标添加到不同的按钮

regex - 为什么零宽度匹配正则表达式不起作用?

regex - 匹配某个单词前后最多 5 个单词

regex - 使用grep搜索find : what is wrong with find .提供的文件 | xargs grep '...' ?

javascript - Q 未处理的拒绝原因与 Q.all

javascript - 未捕获的异常 : ReferenceError: debug is not defined

regex - 在大约 2013 年的编译器中使用 C++11 <regex> 的选项

regex - 在 Perl 中解析 URL 参数