2

I'm writing an application where the user enters JavaScript through the eval() function. Is it possible to identify statements and functions that were called as part of that code? For example, how many if statements were included in the user code; how many for loops?

Is there an alternative to eval() or API package (that can be used in-browser as opposed to NPM or linked through CDN) that could be used instead?

I am aware of the security and performance issues around eval() and, at this stage at least, they are not a concern.

Many thanks in advance - Jim

Ketilbert
  • 31
  • 1
  • you can count `if` statements and `for` loops in source code without the need to `eval`'it – GrafiCode Feb 24 '20 at 17:40
  • as per code analysis, there are many resources on the web: https://www.softwaretestingmagazine.com/tools/open-source-javascript-code-analysis/ – GrafiCode Feb 24 '20 at 17:42
  • `code.match(/if/g).length` – Jonas Wilms Feb 24 '20 at 17:46
  • 1
    No, there is no native parser for js code. You are looking for an AST parser, you can find many libraries for that. – Bergi Feb 24 '20 at 17:47
  • Hi GrafiCode, I need to use eval as it is the user that inputs code and I need some way to analyse that code. Thanks - Jim – Ketilbert Feb 24 '20 at 17:47
  • @JonasWilms `code = "fails if 'if' is contained in string literals"; // or comments` – Bergi Feb 24 '20 at 17:47
  • @bergi [I can parse JS with Regex!](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) :) – Jonas Wilms Feb 24 '20 at 17:48

0 Answers0