Executing a function without using the eval() function

I am currently working on a JavaScript code that relies heavily on the eval function.

eval(myString)

The value of myString is equal to myFunc(arg), and I would like to find a way to call myFunc directly instead of using eval.

Unfortunately, I have no control over which function needs to be called, as it comes in the form of a string (myString). The arguments for that function are also included within the same string.

Is there any alternative method that would allow me to execute the desired function without resorting to eval?

Answer №1

I have reservations about allowing users to input function names, but for the sake of discussion, let's say you have the function name stored in a variable and the argument value in another variable. Here's how you could go about it:

var myString = window[fn](arg);

The argument arg is likely already passed as an argument, making that part straightforward. The challenge lies in extracting the function name. A simple regex solution could be:

var fn = /^([a-z0-9_]+)\(arg\)$/i.exec(str)[1];
if (fn && typeof window[fn] === 'function') {
  window[fn](arg);
}

This code assumes that the function always exists in the global scope. If not, adjustments will need to be made. Additionally, keep in mind that the regex provided may not cover all possible function names.

If you wish to restrict the string to specific functions (which is advisable), this can be achieved once you have the function name:

var allowedFunctions = {fn1: fn1, fn2: fn2, someOtherFunction: function() {} },
    fn = /^([a-z0-9_]+)\(arg\)$/i.exec(str)[1];

if (fn && allowedFunctions[fn]) {
    allowedFunctions[fn](arg);
} else {
    // Nice try.
}

(Note that if arg is not a variable name but rather a literal or complex expression, the process becomes more intricate and less secure.)

Answer №2

Utilizing JavaScript to call a function represented as a string is limited, with the only real option being to use Eval. While some may argue against its usage, sometimes it's the only choice available.

Answer №3

One potential solution could involve utilizing the Function method:

var verify = function(message) {
  return confirm(message);
};
var message = 'verify("Are you sure?")';
var result = new Function('return ' + message)();
alert(result);

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

Dealing with a windows-1250 URI within a node.js/express framework

My application relies on a web service to generate its URIs, which sometimes results in a (potentially) windows-1250 encoded string (/punk%92d). Unfortunately, Express encounters an error: Connect 400 Error: Failed to decode param 'punk%92d' ...

Updating item information within an array in Vue.js

I'm currently working on integrating an edit feature into a task application using Vue JS. My issue lies in the fact that I have a click event assigned to the edit button - @click="editShow" which displays input fields for editing all items instead ...

What are the steps for displaying multiple input fields using the onchange method?

$(document).on("change","#noofpack",function(){ count = $(this).val(); for(i=1;i<=count;i++){ $("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">'); ...

Assigning the Style property to an element using a string that includes HTML tags

My HTML string is populated with elements such as button, li, span, and more. I am looking to add specific styles to buttons based on their class name. For example, if button.btn { some styles } and button.btn-success { some other styles } O ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

The usage of Arrow Functions within Object Literal Syntax

I can't seem to understand why an arrow function within an object literal is invoked with window as the context for this. Any insights on this would be greatly appreciated. var arrowObject = { name: 'arrowObject', printName: () => { ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

Leveraging node.js for website development

After setting up Node.js and installing the latest version of Express 3.4.1, I started coding. However, when trying to send parameters other than /, I encountered an error. In my index.js file, I have the following code: exports.speakers = function(req, ...

The URL in React Router updates as expected, but when attempting to render a component using a button component link

I have encountered a situation similar to the one portrayed in this CodeSandBox example, where I am required to implement react routing within two distinct components. The issue that is perplexing me is that, when I navigate down to either the Profile or ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

Is there any difference in loading speed when using an async function in the createConnection method of promise-mysql?

Is it more efficient to use asynchronous createConnection or not? Does this impact the loading speed in any way? I am working with express, ReactJS, and promise-mysql. Which approach is preferable? Option 1: async connect () { try{ ...

How to retrieve multiple values from a single select dropdown form field using React

In my React Material form, I have a select dropdown that displays options from an array of objects. Each option shows the name field, which is set as the value attribute (cpuParent.name). However, I also need to access the wattage field (cpuParent.wattage) ...

JavaScript not functioning properly with HTML loaded via .load()

I'm facing a perplexing dilemma: My issue revolves around this JS code: EDIT updated JS $(".img-thumb").on("click", function(){ // displaying the same behavior as .click() thumbID = $(this).attr("id"); console.log(thumbID); $(".gal-act" ...

Guide to placing a button on the same line as text with the use of JavaScript

Does anyone know how to add a button to the right of text that was added using JS DOM? I've tried multiple techniques but can't seem to get it right - the button always ends up on the next line. Any tips on how to achieve this? var text = docu ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

A step-by-step guide on how to refresh a circular loading indicator

I have been researching how to create a circular progress bar using canvas, and I came across this code. After making some modifications to the code snippets that I found online, I encountered an issue - I can't seem to reload the circular path once i ...

Error message: Requesting server-side file requires JavaScript to be enabled

This issue has been quite a challenge for me, as it appears to be straightforward but has turned into a complex problem. I have a vue application that utilizes canvas to draw images. I want an API to determine the 'type' of image to display (fil ...

How to Avoid Duplicating Documents in MongoDB?

I'm currently exploring effective methods to avoid saving duplicate documents in MongoDB. Currently, my form captures the user's URL input. The workflow is as follows: Validate if the user's URL is valid (using dns.lookup). If the use ...

Is there a way to extract the text that lies between two closed HTML

Looking for a solution using jQuery. <pre><marker id="markerStart"></marker> aaaaa <span style='font-family:monospace;background-color:#a0a0a0;'>bbb</span>bb cc<marker id="markerEnd"></marker>ccc </pr ...