2

I'm a newbie so forgive me if my terminology doesn't make sense. Here goes....

If I have the following variables in JS:

var LE_TotalAnnualIncome = "50000";
var LE_TypeOfSP = "Single";
var LE_NoDependants = "1";
var LE_Customer = "3000";

How can I convert the string:

MinimumLivingExpenses(LE_TotalAnnualIncome,LE_TypeOfSP,LE_NoDependants,LE_Customer)

To:

MinimumLivingExpenses("50000","Single","1","3000")

Edited to add this: This code might explain what I'm trying to achieve:

function Calculate()
{
var elements = frm_livingexpenses.elements;
var el;
var reClass = /(^|\s)inputCalculated(\s|$)/;

// Searches for fields that need to be calculated
for (var i=0, iLen=elements.length; i<iLen; i++) 
{
    el = elements[i];
    if (reClass.test(el.className))
    {
        // if contents of element are a formula, calculate result
        // the element will have an '=' if it's a formula
        var GetFormula = document.getElementById(elements[i].name).getAttribute('data-formula');
        if (GetFormula.substring(0,1) == '=')
        {
            elements[i].value = eval(GetFormula.substring(1,999));
            eval(elements[i].name.substring(12,999) + '="' + elements[i].value + '";');
            // this is where the variables are set. eg
            // var LE_TotalAnnualIncome = "50000";
            // var LE_TypeOfSP = "Single";
            // var LE_NoDependants = "1";
            // var LE_Customer = "3000";
        }

        // if contents of element are a function call, send to function
        // the element will have a '#' at the front if I need to call a function
        if (GetFormula.substring(0,1) == '#')
        {
        // eg. #MinimumLivingExpenses(LE_TotalAnnualIncome,LE_TypeOfSP,LE_NoDependants,LE_Custo‌​mer)
        // this should be:  MinimumLivingExpenses("50000","Single","1","3000")
        alert('Ajax call will use this in URL='+GetFormula.substring(1,999));
        }
    }
}

}`

AussieM8
  • 37
  • 6
  • Passing variables to a function is fine. What's the problem? – Marcos Pérez Gude May 26 '16 at 16:21
  • 1
    can you please provide an example of how you are using `MinimumLivingExpenses` in your code – CaffeineAddiction May 26 '16 at 16:21
  • 1
    Which part of your first version doesn't work? If I understand you correctly, you want to call your function which accepts strings as parameters. Passing the strings as variables should be completely fine. – Keiwan May 26 '16 at 16:22
  • OK, really appreciate everyone answering. I'm pulling the string "MinimumLivingExpenses(LE_TotalAnnualIncome,LE_TypeOfSP,LE_NoDependants,LE_Custo‌​mer)" from a database and then putting that into an element. When I retrieve that element, I'm wanting to send an Ajax call (but substituting the actual values instead of the text for each variable). – AussieM8 May 26 '16 at 22:16
  • @AussieM8 Check my updated answer. You really should have provided some initial clarification, mate. – Marian May 27 '16 at 01:10
  • Sorry, I'm a bit new to StackOverflow so didn't want to over-complicate what I'm trying to achieve. I now see that it's better to show the actual code so others can interpret what the hell I'm on about :) – AussieM8 May 27 '16 at 02:53

2 Answers2

0

One way to achieve what you want is creating an object to store the variables. Notice the added benefit of not evaling anything. In order to do it:

  • Define the object:

    var reClass = /(^|\s)inputCalculated(\s|$)/;
    var variables = {};
    
  • Add the variables as properties using bracket notation - just change your eval() to this:

    // Empty string concatenation to make sure the value stored is cast to string
    variables[elements[i].name.substring(12,999)] = '' + elements[i].value;
    
  • Construct the string by getting values from the object. Notice that I create a new list of variables, instead of simply going through all properties of the object. The reason is that looping through object properties doesn't guarantee any kind of order.

    First build the list and save it to a variable (choose one way):

    // First, split into two by finding the opening parenthesis - .split()
    // Get the part that comes after it - [1]
    // Get rid of the second parenthesis - .slice()
    // Make an array from the names by splitting on commas - .split()
    var arguments = GetFormula.split('(')[1].slice(0, -1).split(',');
    
    // Also another way to do it with a regexp (Does the job, looks bad)
    // Splits on both parenthesis, gets what's in between of them
    // Then split on commas to make an array
    var arguments = GetFormula.split( /[\(\)]/ )[1].split(',');
    

    Finally, start constructing the final string:

    // GetFormula string, from after '#' and until '('  - included
    // e.g. 'MinimumLivingExpenses('
    var finalString = GetFormula.slice(1, GetFormula.indexOf('(') + 1);
    
    // For each argument, get its value from the object,
    // surround with quotes and add a comma
    arguments.forEach(function(argument){
        finalString += '"' + variables[argument] + '",';
    });
    
    // Replace the last comma with a closing parenthesis
    finalString = finalString.slice(0, -1) + ')';
    
    // Or another way to do it - with a regexp
    // finalString.replace(/,$/, ')')
    
    alert('Clarifying your question got you this string:' + finalString);
    

Update I don't know, what comes in the name in the first 12 chars, that you are only getting the next 999 chars, which is why I left your logic unchanged. But you could use name.slice(12) to get from 12th index to the end of the string.

Community
  • 1
  • 1
Marian
  • 3,789
  • 2
  • 26
  • 36
  • Could you explain how your answer addresses the problem(s) from the question? Code-only answers are not very useful, especially for further readers that stumble upon this post. Thanks! – Cristik May 26 '16 at 19:28
  • @Cristik Now it does, since the question finally makes the task clear. I thought, that the cryptic code I wrote did just what the question was about. – Marian May 27 '16 at 01:14
  • Wow ... thanks for the detailed answer. The first 12 chars is just 'FormElement_' and then after that it's the variable name. I won't be able to test/put it into practice until later tonight but it's obvious I have a lot to learn. Great comments hlfrmn too (sorry I can't upvote until I've got more rep points). – AussieM8 May 27 '16 at 02:57
0

If you really mean you want to do a substitution in a string, then you can use replace for that:

var LE_TotalAnnualIncome = "50000";
var LE_TypeOfSP = "Single";
var LE_NoDependants = "1";
var LE_Customer = "3000";
    
var str = "MinimumLivingExpenses(LE_TotalAnnualIncome,LE_TypeOfSP,LE_NoDependants,LE_Customer)";
str = str.replace("LE_TotalAnnualIncome", LE_TotalAnnualIncome)
         .replace("LE_TypeOfSP", LE_TypeOfSP)
         .replace("LE_NoDependants", LE_NoDependants)
         .replace("LE_Customer", LE_Customer);
console.log(str);

When called with a string as the first argument, it will replace the first occurrence of that string with the second argument.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875