正则表达式中的文字美元符号 [英] Literal dollar sign in a regular expression

查看:413
本文介绍了正则表达式中的文字美元符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用加拿大(fr-CA)语言环境,并尝试执行以下操作:

I am working with Canada (fr-CA) locale and trying to do following:

var str = "<dataset >{1}</dataset>";
var temp = "<set Cost x = '1,8M $' />";

str = str.replace(/\{1\}/g, temp);

输出:

"<dataset ><set Cost x = '1,8M  </dataset>" /></dataset>"

期望的输出:

"<dataset ><set Cost x = '1,8M $'" /></dataset>"

replace函数将'1,8M $'中的$'误认为是表达式,因此
在输出中重复.有任何想法/解决方法吗?谢谢您的时间.

replace function is misunderstanding $' from '1,8M $' as an expression and hence
repeating in the output. Any ideas/workaround? Thank you for your time.

推荐答案

$'在使用JS正则表达式时在替换字符串中具有特殊含义:它将插入匹配的子字符串之后的字符串部分.要在替换字符串中获得文字美元符号,请使用$$.

$' has a special meaning in the replacement string when using JS regular expressions: it inserts the portion of the string that follows the matched substring. To get a literal dollar sign in the replacement string, use $$.

请参见 https://developer.mozilla .org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace .

这篇关于正则表达式中的文字美元符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆