Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace

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?

like image 517
tsh Avatar asked Jan 23 '15 03:01

tsh


People also ask

How to replace string in string js?

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.

How to replace using RegEx in JavaScript?

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.

How to replace a character in a string in JavaScript?

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.


1 Answers

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 });
}
like image 119
Leonid Avatar answered Sep 20 '22 02:09

Leonid