3

I'm trying to create a find and replace program. The problem is that everything that goes inside the global match modifier is converted to a string. How do I prevent that so I can use a variable as the value of the global match modifier?

the code :

function replaceHim() {

    var para = document.getElementById("para");
    var replaced = document.getElementById("firstInput").value;
    var replaceWith = document.getElementById("secondInput").value;
    var paraValue = para.innerHTML.replace(/replaced/g,replaceWith);
    para.innerHTML = paraValue;
}
isherwood
  • 52,576
  • 15
  • 105
  • 143
doubleOrt
  • 2,289
  • 1
  • 13
  • 31

1 Answers1

3

In this case you need to use RegExp constructor to create a dynamic regular expression object:

function replaceHim() {
    var para = document.getElementById("para");
    var replaced = document.getElementById("firstInput").value;
    var replaceWith = document.getElementById("secondInput").value;
    var regexp = new RegExp(replaced, 'g');
    var paraValue = para.innerHTML.replace(regexp, replaceWith);
    para.innerHTML = paraValue;
}

Note, that in this case it's very important that the value passed into RegExp constructor is properly escaped.

Community
  • 1
  • 1
dfsq
  • 187,712
  • 24
  • 229
  • 250