-2

I have a code saved in string. For eg:
const code = "res.send("Hi")";
How can I execute the above code in JS? I wanna execute the code of the code variable.
I can't just write code;. The code doesn't execute. Please Help.

7
  • 6
    eval(code) - but be careful, that is risky. Commented Jun 19, 2022 at 18:07
  • 1
    Sounds like an XY problem. Why do you need this? What is the context? Commented Jun 19, 2022 at 18:08
  • 1
    I need it to send message to multiple sockets Commented Jun 19, 2022 at 18:16
  • 2
    Then use a loop to chain the .to() so you don't have to use a string. Having it in a string is not the way to go here. Commented Jun 19, 2022 at 18:28
  • 2
    @Ivar Thats a good way to do it. I'll use it instead of combining in string. Commented Jun 19, 2022 at 18:35

1 Answer 1

2

use eval

const code = "console.log('Hi')";

eval(code)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.