const regex = /(\(\s?function+.formula.*\{\s?)([\w|\.]+\s?=[^\}]*)(\s?\}\s?\)\s?\(\s?\)\s?;)/gi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\(\\s?function+.formula.*\\{\\s?)([\\w|\\.]+\\s?=[^\\}]*)(\\s?\\}\\s?\\)\\s?\\(\\s?\\)\\s?;)', 'gi')
const str = ` (function Formula(x){ ListaOP.FormaPActiva.RemanenteACancelar = ListaOP.OPActiva.TotalesCliente.Total - ListaOP.OPActiva.MontoAcumuladoFormasPago; })(variableX);
(function Formula() { ListaOP.FormaPActiva.ImporteACancelar = ListaOP.FormaPActiva.RemanenteACancelar; })();
(function formula(){ a=b; })();
if (!v.Parametros.AfectarGastoEnvioRecargoFinanciero && ListaOP.OPActiva.MontoCanceladoContado < v.GastoEnvio + v.GastoEnvioImpuestoCliente) {
(function formula() { ListaOP.FormaPActiva.RemanenteACancelar = ListaOP.FormaPActiva.RemanenteACancelar - v.GastoEnvio - v.GastoEnvioImpuestoCliente; })();
}
var c = function(){
};
(function Formula() { ListaOP.FormaPActiva.ImporteFinanciamientoTotal = ListaOP.FormaPActiva.RemanenteACancelar * (ListaOP.FormaPActiva.CoeficienteFinanciacion - 1); })();
(function Formula() { ListaOP.FormaPActiva.ImporteACancelar = ListaOP.FormaPActiva.ImporteACancelar + ListaOP.FormaPActiva.ImporteFinanciamientoTotal; })();
(function Formula(x) { ListaOP.FormaPActiva.RemanenteACancelar = ListaOP.FormaPActiva.ImporteACancelar; })(10);`;
const subst = `Calcular('$2'); `;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions