How can I replace JS eval function with more secure solution?
const textarea = document.getElementsByTagName("textarea")[0];
const tooltip2 = document.querySelectorAll(".tooltip2");
const hiddenTooltip = document.querySelectorAll(".hiddenTooltip");
let replaced = 'textareaValue';
for (let i = 0; i < tooltip2.length; i++) {
replaced += '.replace(/' + tooltip2[i].innerText + '/g,' + "'" + hiddenTooltip[i].innerText + "'" + ')'
}
replaced += ';';
textarea.value = eval( replaced );
This code works, eval function changes string to expression, but I read that’s not secure. I should have something like this:
let replaced = textareaValue.replace(/kga/g,'całkowite opracowanie ubytku, selektywne wytrawianie, UB, Gradia A3').replace(/ksc/g,'scaling nad i poddziąsłowy, fluoryzacja na łyżkach').replace(/ksn/g, 'scaling naddziąsłowy, fluoryzacja na łyżkach').replace(/ksp/g, 'scaling poddziąsłowy, fluoryzacja na łyżkach').replace(/kwg/g, 'całkowite opracowanie ubytku, wypełnienie glasjonomerowe');
I have PHP code to add or remove shortcuts dynamically. My PHP code works.
I tried trick with new Function, but it doesn’t work.
textarea.value = new Function('return ' + replaced)();
Could you give me a solution to my problem?
>Solution :
You don’t need eval for this at all. Just call .replace() repeatedly in the loop:
for (let i = 0; i < tooltip2.length; i++) {
const search = new RegExp(tooltip2[i].innerText, 'g');
const replacement = hiddenTooltip[i].innerText;
textareaValue = textareaValue.replace(search, replacement);
}