'Converting `eval` statements to functions (implicit return)

I have developed a large number (>1000) strings that are intended to be fed into eval. I am trying to migrate away from using eval, as "eval is evil" and I'm generally trying to make things more secure. However, migrating from eval into a properly defined function is a little tricky, as eval() returns the value of the last expression evaluated. This means that a string that was previously evaled like this:

const stringToEvaluate = "x = 1; x + 1"

is difficult to migrate directly into a function, because the last expression in the statement does not explicitly return anything. With regards to the string above, I might use eval in this way:

const y = eval(stringToEvaluate)
console.log(y) // 2

However, I can't use:

const y = (function safeFunction() {
   x = 1;
   x
})()
console.log(y) // undefined

as safeFunction does not return anything.

Importantly, I am looking for a way to migrate these eval strings without needing to modify each individual string to include return statements in appropriate places. This is because the large number of scripts would make this quite inconvenient. Also, the scripts can be more complicated than this, but this is a nice, minimal example.

Does anyone happen to know of any way to migrate these scripts into functions without needing to manually edit each of them? Also, this is one my first times posting to StackOverflow, so I welcome any feedback about ambiguity in my question! Thanks!

Edit: Apologies for the ambiguity, another example of a "string" to be converted into a script is:

const stringToEvaluate = """
let x; 
if (
    $('.itemToFind').length > 0 &&
    $('.itemToFind').html().trim() != ''
  )
    $('.itemToFind del').html().trim();  <<< eval wraps either this
  else if ($('.price h4.offer-price').length > 0)
    $('.itemToFind').html().trim();      <<< or this
"""

(note that I have included the string across multiple lines to aid readability).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source