Javascript Regex Function replace()
Javascript Regex Function replace()
我刚开始学习JavaScript。我有一个String
var str2= "1 dollor plus 2 dollor equal 3 dollor";
我想转换成
$1 plus $2 equal $3
所以我使用函数Replace()像这样:
str2 = str2.replace(/('d+)'s/g, ''$$&");
str2 = str2.replace(/dollor/g, '');
但是我得到这个str:
$& plus $& equal $&
我这样修改我的代码:
str2 = str2.replace(/('d+)'s/g, ''$'+"$&");
它不工作。我知道我的问题可能很蠢。但是我真的不知道为什么"'"不能转义"$"。原谅我的英语不好!
根据这里的文档,$
的替换字符串是$$
,而不是'$
。考虑到这一点,在您的第一个替换行中使用以下命令来生成您想要的输出:
str2 = str2.replace(/('d+)'s/g, '$$$&');
这样做:
var str2= "1 dollor plus 2 dollor equal 3 dollor";
str2 = str2.replace(/('d+)'s/g, function replaceWithReposition(x){return "$" + x});
我为你准备了一把小提琴:https://jsfiddle.net/mez2yqb1/
相关文章:
- 直接在函数声明上使用function.prototype.bind
- jQuery:.click(function(){(element),collapse('show',f
- 如果连接类型为none,则Javascript Function Only警报
- onLoad function phonegap android
- 替换变量时,JavaScript字符串replace()不起作用
- reducers在redux中得到Function not Object,what'it’他错了
- Javascript 如何强制 string.replace 不将我的字符串解释为正则表达式
- 如何在做PHP时在base64中动态编码;preg_ replace”;
- WIll window.addEventListener(“加载”,function(),false);等待浏览器自动填
- 我使用了replace(“[^-A-Za-z0-9()%.],但它为'我可以解决这个错误吗
- $(document).ready和jQuery(function($)不工作;jQuery已定义,但脚本尚未定义;t进
- Regex Replace仅适用于Last Match
- 如何在Java中实现与JavaScriptString.replace(RegEx,function)相同的功能
- jQuery href replace function not updatting
- JS | replace using function | meaning of (a,b,c)
- Javascript参数化字符串:replace(RegExp, function)意外分组/匹配
- 在哪里可以找到Javascript的文档's`string.replace(RegExp,function)`方
- 在JavaScripts "replace" function中指定某些字符作为变量
- Javascript Regex Function replace()
- 获取RethinkDB中replace(function(){})中的实际字段值