Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 799335
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T23:06:34+00:00 2026-05-14T23:06:34+00:00

Is there a way to resolve mathematical expressions in strings in javascript? For example,

  • 0

Is there a way to resolve mathematical expressions in strings in javascript? For example, suppose I want to produce the string “Tom has 2 apples, Lucy has 3 apples. Together they have 5 apples” but I want to be able to substitute in the variables. I can do this with a string replacement:

string = "Tom has X apples, Lucy has Y apples. Together they have Z apples";
string2 = string.replace(/X/, '2').replace(/Y/, '3').replace(/Z/, '5');

However, it would be better if, instead of having a variable Z, I could use X+Y. Now, I could also do a string replace for X+Y and replace it with the correct value, but that would become messy when trying to deal with all the possible in-string calculations I might want to do. I suppose I’m looking for a way to achieve this:

string = "Something [X], something [Y]. Something [(X+Y^2)/(5*X)]";

And for the [___] parts to be understood as expressions to be resolved before substituting back into the string.

Thanks for your help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T23:06:35+00:00Added an answer on May 14, 2026 at 11:06 pm

    There’s no direct, built-in way (well, okay, perhaps there is — see below), but if you use the callback feature of the replace function, where the replacement can be a function rather than a string (the return value is what’s substituted in), you can implement this fairly easily.

    For instance, suppose you use the Ruby notation #{xyz} for your placeholders. This code loops through those:

    var mappings, str;
    
    str = "One #{X} three #{Y} five";
    mappings = {
        "X": 2,
        "Y": 4
    };
    str = str.replace(/\#\{([^#]+)\}/g, function(match, key) {
        var result;
    
        result = mappings[key];
        /* ...processing here */
        return result;
    });
    

    The resulting string is One 2 three 4 five, because #{X} and #{Y} have been replaced via lookup. You can look at the key and see whether it’s an expression and needs to be evaluated rather than simply looked up. That evaluation is where your real work comes in.

    Now, you could use with and eval to achieve expression support; change the result = mapping[key]; line above to this:

        with (mappings) {
            result = eval(key);
        }
    

    If you feed the string "One #{X} three #{Y} five #{X + Y * 2}" into that, the result is One 2 three 4 five 10 — because 2 + 4 * 2 = 10.

    That works because with sticks the given object on top of the scope chain, so it’s the first thing checked when resolving an unqualified reference (like X), and eval executes Javascript code — and so can evaluate expressions — and magically does so within the scope in which it’s called. But beware; as Eric pointed out, not all operators are the same in various forms of expression, and in particular Javascript interprets ^ to mean “bitwise XOR”, not “to the power of”. (It doesn’t have an exponent operator; you have to use Math.pow.)

    But you need to be very careful about that sort of thing, both with and eval (each in their own way) can be problematic. But the main issues with with are that it’s hard to tell where something comes from or where it will go if you do an assignment, which you’re not; and the main issues with eval come from using it to interpret strings you don’t control. As long as you keep safeguards in place and are aware of the issues…

    Boiling that down into a function:

    function evaluate(str, mappings) {
        return str.replace(/\#\{([^#]+)\}/g, function(match, key) {
            var result;
    
            with (mappings) {
                result = eval(key);
            }
    
            return result;
        });
    }
    alert(evaluate(
        "The expression '(#{X} + #{Y}) * 2' equals '#{(X + Y) * 2}'",
        {"X": 2, "Y": 4}
    )); // alerts "The expression '(2 + 4) * 2' equals '12'"
    alert(evaluate(
        "The expression '(#{X} + #{Y}) * 2' equals '#{(X + Y) * 2}'",
        {"X": 6, "Y": 3}
    )); // alerts "The expression '(6 + 3) * 2' equals '18'"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 430k
  • Answers 430k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer From the man find page: -regex pattern File name matches… May 15, 2026 at 2:03 pm
  • Editorial Team
    Editorial Team added an answer You asked two questions: Deep vs. shallow copy matrix[:] is… May 15, 2026 at 2:03 pm
  • Editorial Team
    Editorial Team added an answer You almost never need to use for-each in XSL, and… May 15, 2026 at 2:03 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.