Change the behavior of eval() to interpret '%' as 'per 100'

Is there a way to modify eval() so that it replaces % with /100? I have an app where I receive dynamic formulas that need to be evaluated. The problem arises when the formula includes %. For example:

E_LOW%*CT_TOTAL+(1-GQC)

where E_LOW, E_TOTAL, GQC are constants.

For instance:

E_LOW = 10

I expect E_LOW% to be interpreted as 0.10, i.e., E_LOW% = 10/100 = 0.10

Currently, I am encountering the following error:

SyntaxError: Unexpected token *

Please note: The issue does not lie with *. Even attempting eval(E_LOW%) results in the error:

SyntaxError: Unexpected token )

It seems that eval is unable to understand or process anything after the %.

Thank you in advance

Answer №1

To solve this problem, you can substitute the percentage sign % in the calculation string with /100 and then calculate the result.

var E_LOW = 10,
    calculation = 'E_LOW%',
    replaced = calculation.replace(/([a-z_]+)%/gi, '($1/100)'),
    result = eval(replaced);

console.log(replaced);
console.log(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

What is the best way to transfer data from app.post to app.get when navigating between multiple pages?

Within my app.js file, I am encountering a challenge as I aim to transfer the username inputted in a form on the login page over to the game page. Despite having successfully retrieved the data using req.body.username within app.post('/login'), I ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

error encountered in NestJS: unable to modify headers once they have been sent

request /login/login.html redirect /login I made a change to the redirect within the interceptor export class UricheckInterceptor implements NestInterceptor { constructor(private uri: string[]) {} intercept(context: ExecutionContext, next: CallHa ...

Creating a TypeScript map with conditional items

I encountered an error while trying to add an item conditionally to a Map using .filter, receiving the message Type 'null' is not assignable to type 'readonly [string, Book]'.(2769). This issue seems to arise only when adding items cond ...

Is there a way for me to figure out if a Primefaces RadioCheckbox has been selected?

Despite the numerous examples available on how to count checked checkboxes, I am facing difficulties in getting it to work. My goal is to enable a button when at least one checkbox is checked on the page, and disable it when none are selected. However, n ...

Is there a way to add a <video> tag in tinymce editor without it being switched to an <img /> tag?

I am attempting to include a <video> tag within the tinymce editor, but it keeps changing it to an <img> tag. Is there a way to prevent this conversion and keep the <video> tag intact? I want to enable videos to play inside tinymce whil ...

Keep deciphering in a loop until the URI string matches

I have a task to decode a string URI until there are no more changes. The string URI I am working with typically has around 53,000 characters, so the comparison needs to be fast. For demonstration purposes, I have used a shortened version of the string. B ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Tips for implementing the find() method on Nested Objects

I'm attempting to locate and return the object inside comments_text that contains a key matching findKey. const findKey = "-MkeQEa2sgCho_ijk7TO" const posts = [ 0:{ comment: false, comments_text: { 0: { ...

Tips for incorporating Emoji into a messaging platform similar to SendBird (non-native, web-based application)

Hey everyone! I'm currently working on a project that involves integrating the "SendBird" messaging service. I've successfully implemented all the basic functions, but now I want to incorporate Emoji for better user experience. I'm feeling a ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Looking to switch up the thumbs-up button design?

I am a beginner in using jquery and ajax, and I need some assistance. How can I incorporate this jquery code into my logic: $('.btn-likes').on('click', function() { $(this).toggleClass('liked'); }); Can so ...

Specify the minimum required spacing between two meshes in THREE.JS

I'm working on a code that generates clouds with random positions, rotations, and scales. However, sometimes these clouds can end up clipping together when they are generated close to each other or near another object. I want to set a minimum distance ...

Steps to seamlessly integrate puppeteer with an active Chrome instance or tab

Is there a way to connect puppeteer to an already open Chrome browser and control a specific tab? I believe it may involve starting Chrome with the --no-sandbox flag, but I am unsure of the next steps. Any assistance on this matter would be greatly apprec ...

A specialized wrapper for push notifications in Cordova that utilizes observables for streamlined

When working with the phonegap-plugin-push for cordova, you will come across various functions that use the following syntax: function name(successCallback(),errorCallback(),options) I am interested in creating a wrapper function that returns an Observab ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

What is the proper way to add data to an HTML page using JQuery and Ajax?

I'm currently in the process of setting up a feature for displaying more articles using Python, Flask, and Ajax. The backend functionality is all set up and running smoothly, but I'm stuck on how to incorporate the new data into the HTML using jQ ...

Loading and linking JavaScript and JSX files

Working with ReactJS has been smooth sailing when it's all contained in one file. I've been loading it using the code <script type="text/babel" src="js/test.js"></script>. For some reason, using "text/javascript" causes issues with r ...

Send the output of an asynchronous ajax request to the designated function within the jQuery Validation plugin

Utilizing the jQuery Validation plugin (JVP) for server-side validations via ajax has been seamless, except for one hitch: JVP struggles with performing remote validation on blank fields. While it's easy to use its default required: true rule for sim ...