Evaluate the Javascript string and save the output

My challenge involves receiving JavaScript as a string that needs to be executed and compared to a specific output. Currently, I am utilizing the eval() function for this task, but I am open to alternatives. The execution takes place on the client side within a web browser.

Is there a method to accomplish this without modifying the string a?

let a = "console.log(\"a\")";
eval(a);
let stdout = ???

Answer №1

Utilizing:

  • bind()
  • call()

One can enhance console.log to maintain an additional, separate real-time log of all the entries.

In the practical example provided below, each time something is logged to the console, it is also appended to the console.stdout array.


Practical Example:

console.stdout = [];
console.logInclStdout = console.log.bind(console);

console.log = (logEntry) => {
    console.stdout.push(logEntry);
    console.logInclStdout.call(console, logEntry);
}


let a = "console.log('a')";
let b = "console.log('b')";
let c = "console.log('c')";

let saferFasterEval = (input) => Function(`"use strict"; ${input}`)();

saferFasterEval(a);
saferFasterEval(b);
saferFasterEval(c);

// To view the logs made via console.log
console.info(console.stdout);

Answer №2

To preserve the messages outputted through console.log within the eval function, one approach could involve replacing the console.log function. However, it is generally advised against this practice and using eval altogether.

// Save the original console.log function
const original = console.log;

// Initialize an array to store the commands
const commands = [];

// Override console.log to capture the logs
console.log = (msg) => { commands.push(msg) };

// Execute operation A
let a = "console.log(\"a\")";
eval(a);

// Execute operation B
let b = "console.log(\"b\")";
eval(b);

// Execute operation C
let c = "console.log(\"c\")";
eval(c);

// Retrieve the log messages; Convert them to a string using `commands.join('\n')`
let output = commands;

// Restore the original console.log
console.log = original

Sample: https://jsfiddle.net/x0w2q4Le/4/

Answer №3

When using eval function, the output can be stored in a variable like this:

let x = `
    let num = 5
    num += 2
    num
`
let result = eval(x)

Ensure to place the value you intend to return at the end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you provide some straightforward instances of single-axis zooming using d3?

I'm interested in creating a single-axis zoom for d3's zoom behavior. Are there any straightforward examples that demonstrate how to achieve this? I came across Mike Bostock's example, but I found it a bit complex to grasp. Here is the code ...

Tips for adding a dynamic variable into a react JSX map function

I have a component that receives a props with the value of either 'A', 'B', or 'C' based on the selection made in the parent element. The challenge is to use this props to dynamically select an option list locally, instead of ...

Retrieve the maximum numerical value from an object

My goal is to obtain the highest value from the scores object. I have a global object called "implementations": [ { "id": 5, "project": 'name project', "scores": [ { "id": 7, "user_id": 30, "implement ...

Is the syntax incorrect or is there another reason for the empty array being passed, as the "resolve" callback is running before the completion of the for loop?

The for loop will iterate over the length of req.body, executing a Customer.find operation in each iteration. The resolve function will then be called with an array containing the results of all the find operations. let promise = new Promise(function(res ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

Discover a helpful tip for using Pentadactyl with StackExchange's voting buttons

Does anyone know how to enable hinting for voting arrows on StackExchange using Pentadactyl (a fork of Vimperator)? I've tried removing my .pentadactylrc file and restarting Firefox, but still can't figure out how to upvote questions and answers ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

Utilize PHP in an APP Engine Application to send an email to a Gmail address

I have a project deployed on Google App Engine where I need to send an email once a user submits the contact form. My app is successfully deployed and I have implemented an ajax request to a PHP file, but unfortunately, it's not functioning as expect ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Display or conceal a div element depending on the value selected in Vue.js

I have a Vue.js dropdown and I would like to show or hide my div based on the selected value in the dropdown. The current code is only working for one ID, but I want it to work for all IDs. I want to toggle the visibility of my div based on the option&apos ...

The findOneAndUpdate function in MongoDB is adding a new record into the database

Whenever I make an update API call, I just need to update the serviceActiveFlag status. After the update API call, a new document with an empty vehicle array is created, as shown below: _id:59c76073c11d3929148f500f vehicle:Array _v:0 The ID field will ov ...

Ways to display a collection of random images with a click of a button?

I've created a simple php webpage that is supposed to display random images from my images folder when a button is clicked. However, I'm facing an issue where no images are showing up and I can't seem to pinpoint the problem in my code. ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

How to rearrange the chosen options in an AngularJS ui-select multiple menu

Is there a way to automatically rearrange the order of selected items in AngularJS ui-select multiple? Check out this code snippet, with more examples available on ui-select github <ui-select multiple ng-model="ctrl.multipleDemo.colors" theme="bootstr ...

A Python program that creates an HTML webpage

I am currently working on a Python script that, when launched on localhost with Apache, will generate an HTML page. Here is the script (test.py): #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb cgitb.enable() import cgi form = cgi.FieldStorage() ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

Breaking content into two sections using Javascript or jQuery

Uncertain if Javascript can handle this task, any assistance or advice is appreciated. Consider this scenario: Suppose I have a 6-paragraph long content (text only) being pulled dynamically from the database all at once. This means that all 6 paragraphs a ...

Challenges encountered with extracting information from a JSON dataset

When I make an Ajax POST request, the response I receive is structured like this: { "columns": [ "r" ], "data": [ [ { "extensions": {}, "start": "http://localhost:7474/db/data/node/27 ...