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
  • 58,414
  • 16
  • 114
  • 157
doubleOrt
  • 2,407
  • 1
  • 14
  • 34

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
  • 191,768
  • 25
  • 236
  • 258