JavaScript - 在String.prototype.replace使用的字符串中更好地逃避美元符号 [英] javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace
本文介绍了JavaScript - 在String.prototype.replace使用的字符串中更好地逃避美元符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用另一个替换一个字符串。我发现replaceValue包含$
时,替换将失败。所以我试图通过$$
首先退出$
。代码如下所示:
var str = ...,reg = ...;
function replaceString(replaceValue){
str.replace(reg,replaceValue.replace(/ \ $ / g,'$$$$'));
}
但我认为这是丑的,因为我需要写4美元的标志。 / p>
有没有其他的特征,我需要逃脱?有没有更好的方法呢?
解决方案
有一种方法可以调用替换
允许我们不用担心逃避任何东西。
var str = ...,reg = .. 。
function replaceString(replaceValue){
return str.replace(reg,function(){return 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, '$$$$'));
}
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?
解决方案
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屋!
查看全文