将字符串中的变量值替换为函数调用



我是个新手,如果我的术语没有意义,请原谅我。给。。。。

如果我在JS中有以下变量:

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

如何转换字符串:

MinimumLivingExpenses(LE_TotalAnnualIncome,LE_TypeOfSP,LE_NoDependants,LE_Customer)

收件人:

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

已编辑以添加此:这段代码可以解释我试图实现的目标:

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));
}
}
}

}`

实现所需功能的一种方法是创建一个对象来存储变量。注意不要eval做任何事情的额外好处。为了做到这一点:

  • 定义对象:

    var reClass = /(^|s)inputCalculated(s|$)/;
    var variables = {};
    
  • 使用括号符号将变量添加为属性-只需将eval()更改为:

    // Empty string concatenation to make sure the value stored is cast to string
    variables[elements[i].name.substring(12,999)] = '' + elements[i].value;
    
  • 通过从对象中获取值来构造字符串。请注意,我创建了一个新的变量列表,而不是简单地遍历对象的所有属性。原因是循环对象属性不能保证任何顺序。

    首先构建列表并将其保存到变量中(选择一种方式):

    // 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(',');
    

    最后,开始构建最后一个字符串:

    // 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);
    

更新我不知道前12个字符的名称中有什么,你只得到了接下来的999个字符,这就是为什么我保持你的逻辑不变。但是您可以使用name.slice(12)从第12个索引到字符串的末尾。

如果你真的想在字符串中进行替换,那么你可以使用replace

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);

当以字符串作为第一个参数调用时,它将用第二个参数替换该字符串的第一个

最新更新