-1

I am facing an issue with the replace function in javascript.

"demo text?for test".replace(new RegExp("text?for", 'g'), "text for");

Its return output is "demo text?for test".

I think, I am missing something but I don't know.

Below is my function I used in my application

 var replaceAll = function (targetString, search, replacement) {
            return targetString.replace(new RegExp(search, 'g'), replacement);
        };

 replaceAll("This is my favorite video https://www.youtube.com/watch?v=n3MPiLq0fKc", "video https://www.youtube.com/watch?v=n3MPiLq0fKc", "http://d-d.co/4eDED")

output is "This is my favorite video https://www.youtube.com/watch?v=n3MPiLq0fKc"

Scath
  • 3,777
  • 10
  • 29
  • 40
Naresh Pansuriya
  • 2,027
  • 12
  • 15

1 Answers1

1

Your code works, provided you supply the regular expression as a string enclosed in / and with the special characters properly escaped, like this:

var replaceAll = function(targetString, search, replacement) {
  return targetString.replace(new RegExp(search, 'g'), replacement);
};

console.log(replaceAll("This is my favorite video https://www.youtube.com/watch?v=n3MPiLq0fKc", /video https:\/\/www\.youtube\.com\/watch\?v=n3MPiLq0fKc/, "http://d-d.co/4eDED"))
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75