-1

I have the following function:

function myFunction(str, find, replace) {

 var res = str.replace(new RegExp(find, 'g'), replace);

 document.getElementById("demo").innerHTML = res;

}

Which simply will find and replace on a string that gets passed in. However lets say for example I want to have it find and replace something like [link here]. If I pass [link here] into the function it goes a bit mad and inserts % all over the place in the string. I'm guessing it does not agree with special chars? How can I get it to look for something inside [] ? Or should I just wrap it in something else like -link here-

Mike Young
  • 301
  • 2
  • 4
  • 13

1 Answers1

-1

You must escape the regexp chars and you can do it easily by this regexp:

find = find.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
var res = str.replace(new RegExp(find, 'g'), replace);
document.getElementById("demo").innerHTML = res;

Ofc, its better to encapsulate this functionality in a global function and use it anywhere you need.

abeyaz
  • 2,490
  • 1
  • 14
  • 18