What is the safest way to evaluate a boolean expression that is in string form using JavaScript?

On my quest towards creating a questionnaire, I aim to have questions appear or disappear dynamically based on specific rules represented as strings (e.g.

answers[1] == 'yes' || (answers[2] > 18 && answers[2] < 24)
).

These rules originate from the database and always result in either true or false. If true, the question is displayed, and if false, it remains hidden. Utilizing vue.js for the front-end, these rules are passed as props and need evaluation within a component during runtime.

I am seeking the most effective method to achieve this goal.

  • In preliminary tests, I experimented with eval() which yielded results. However, I acknowledge its safety risks and hence explore other options.

  • One alternative involves replacing instances of "answers[x]" with their corresponding values since they are the only variables accessible. Nevertheless, this approach would still require another string for evaluation.

  • I came across a package named safe-eval that provides a sandboxed eval function where a context can be supplied for access to the answers. While previous versions reportedly had security vulnerabilities, newer updates seem to have addressed them. Would adopting this be a viable solution?

  • Are there any libraries designed to assist in crafting a parser or offering frameworks for rule creation and evaluation?

Edit: My initial inclination towards utilizing safe-eval over custom parser development stems from its ability to evaluate intricate logic without necessitating an extensive class for handling such complexities.

Answer №1

To ensure the string fits your desired format, consider using a regular expression and only proceed with running eval() if it meets the regex criteria. For assistance in creating a regex pattern, I suggest visiting https://regex101.com/

var condition = 'answers[1] > 18';
var regexPattern = /^answers\[\d+\]\s>\s\d+$/;
var answersArray = [8, 27, 64];

if (condition.match(regexPattern))
  console.log(eval(condition));

Answer №2

To handle rules from the database in JavaScript, consider developing a parser to convert them into functions. The approach will vary depending on the specific structure of the rules you are working with. Here's a simple pseudo-code example:

function parse(string) {
    if (string.match("answers[:d] > :d", question_number, threshold)) {
        return function (answers) {
            return answers[question_number] > threshold;
        };
    }
}
...
answers = [...];
var rule = parse("answers[1] > 18");
if (rule(answers)) {
    // answer[1] > 18
}
else {
    // answer[1] <= 18
}

This parsing method offers better security compared to using eval.

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

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

What is the significance of the "component" prop within MUI components?

I am a beginner in React and HTML. Currently, I am using MUI and React to create my own website. I am currently attempting to add an "Upload button" that will allow me to select an image file when clicked. Below is the official implementation: <Button ...

Reducing ObjectId length in node.js with mongoose

Currently, my URLs have a lengthy structure like this: http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=..... Due to the rapid growth in length, I am contemplating the idea of shorte ...

Suggestions on how to refactor redundant code in various peer AngularJS controllers for handling $intervals

In my compact single-page application, I have implemented multiple tabs to display operational status information for different applications. Each tab is associated with a controller that creates $interval objects to make AJAX calls to fetch status data fr ...

What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way: function (Vue, options) { Vue.$detector = new TranslatableStringDetector(); } Utilizing it within a computed property in my component is done l ...

Error: The function Undefined is not recognized by express.io

Struggling to configure express.io with individual files for each route? Check out the examples provided. Currently, I have a typical Express setup that I want to transition to express.io: Project app.js routes servepage.js Views ...

Tips on how to make the cursor blink in an input text box after tab switching

Whenever I click the button, the cursor in the input field blinks. However, the issue arises when I switch to another tab and return to this tab - the cursor is no longer in position and I have to click the input field again. Even after switching tabs an ...

Is it possible to retrieve a file from a POST request in Express and save it

I am attempting to initiate a file download upon receiving a POST request on my server. This is my attempted code: router.post('/generate', function (req, res) { console.log('THIS IS RUNNING'); var file = __dirname + '/blah.tx ...

Is the API for remote asynchronous http calls (Ajax) in Vuejs comparable to that of jQuery?

While Vuejs is known for being more effective than jQuery for DOM manipulation and user interactions handling, I am curious about its performance when it comes to remote asynchronous HTTP (Ajax) calls. I'm looking for a specific Vue.js core API that c ...

"Utilizing AngularJS to apply Filter two times within an ng-repeat loop

I recently started learning about angularjs and am currently grasping the concept of filters. However, I have come across an issue where angularjs is calling the filter twice instead of once as expected. I'm quite puzzled by this behavior and unsure w ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Creating particle animations using Three.js along a curved path

I'm attempting to create an animation where particles move along a specific path, similar to the one showcased in this Chrome experiment: Upon examining the source code of the aforementioned project, I've discovered that they utilize a predefine ...

I am noticing that my state is getting overridden with new posts whenever I add a new one using React hooks and React context. Can

Currently in the process of developing a new app that will allow me to share updates with my friends, essentially a micro-blogging platform. I am eager to explore using React hooks and React's context API to manage updates within the app. In my imple ...

Organizing Jstree on a template to maximize efficiency

Is there a proper way to center jsTree on the template? I attempted to use just <center>, but it resulted in something like this https://i.sstatic.net/LmxUH.png The image demonstrates that it's hard to distinguish between parent and child nodes ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

Understand when my task is complete

Here are the functions I am working on: function parseLinks(links, callback) { var products = []; for (var i = 0; i < links.length; i++) { request(links[i], function (error, response, body) { var product; if (!e ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

If a 401 response is encountered in Next.js, automatically navigate to the login page

In my project, I utilize Next JS middleware to handle redirection to the login page if there is no token available in middleware.ts: import type { NextRequest, NextResponse } from "next/server"; export function middleware(request: NextRequest, r ...

Generate an AngularJS directive on the fly to dynamically capture user input from the freshly created directive

Let's say I have a directive called "foo" with the following content: <div> <label>Enter foo: </label> <input ng-model="myModel"/> </div> Then, I use it in the following way: <foo></foo> <button>Add f ...

What methods can be used to retrieve the public holidays for every year with Laravel and JavaScript?

As a newcomer to web programming, I am currently working on calculating the number of days between two dates while excluding weekends and public holidays specific to our country for each year. I am looking to create a function that allows me to input a ye ...