Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replace JS eval function with more secure function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading