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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With