javascript - 在 String.prototype.replace 使用的字符串中转义美元符号的更好方法 [英] javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace
本文介绍了javascript - 在 String.prototype.replace 使用的字符串中转义美元符号的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用另一个字符串替换一个字符串.我发现当 replaceValue 包含 "$"
时,替换将失败.所以我试图首先通过 "$$"
转义 "$"
.代码如下:
I want to replace a string by another. I found when the replaceValue contains "$"
, the replace will fail. So I am trying to escape "$"
by "$$"
first. The code is looks like this:
var str = ..., reg = ...;
function replaceString(replaceValue) {
str.replace(reg, replaceValue.replace(/$/g, '$$$$'));
}
但我觉得它很丑,因为我需要写 4 个美元符号.
But I think it is ugly since I need to write 4 dollar signs.
还有其他角色需要我逃脱吗?有没有更好的方法来做到这一点?
Is there any other charactors that I need to escape? And is there any better way to do this?
推荐答案
有一种调用 replace
的方法,让我们不用担心逃避任何事情.
There is a way to call replace
that allows us not to worry about escaping anything.
var str = ..., reg = ...;
function replaceString(replaceValue) {
return str.replace(reg, function () { return replaceValue });
}
这篇关于javascript - 在 String.prototype.replace 使用的字符串中转义美元符号的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文