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?
replace() The replace() method returns a new string with some or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
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 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With