Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variables and regular expressions

Tags:

javascript

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;
}
like image 761
doubleOrt Avatar asked Dec 27 '25 23:12

doubleOrt


1 Answers

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.

like image 90
dfsq Avatar answered Dec 30 '25 13:12

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!