Got more questions? Find advice on: ASP | SQL | XML | Windows
Welcome to RegexAdvice Sign in | Join | Help

Optimizing a string replacement algorithm in javascript

  •  05-09-2011, 12:04 AM

    Optimizing a string replacement algorithm in javascript

    Ok so I have a rather slow algorithm that I would really love some advice to speed up! It may repeat many times over different large data strings. The string 'data' contains "variables" (denoted by ${myVarName} in the data) that must be replaced with the value of the corresponding (either by id or name) element on the html page. I use javascript and jquery to do this. In particular, the line '\\$\\{'+rVars[key].replace(/([(])/g,"\\(").replace(/([)])/g,"\\)")+'\\}' surely can be replaced with some more efficient regex that I am not wizardy enough to invent. Perhaps I should be approaching this an entirely different way? I appreciate any help or advice!
     

    remainingVars = data.match(/\$\{.*?\}/g);
    rVars = new Array();
    reg = '';
    if(remainingVars != null) {
    for(key=0; key<=remainingVars.length; key++) {
    if(remainingVars[key] != undefined && remainingVars[key].length != undefined) {

    rVars[key] = remainingVars[key].substr(2,remainingVars[key].length-3);

    // In practice the following $('body') call is refined to a smaller context. 
    varVal = $('body').filter('[name="'+rVars[key]+'"],[id="'+rVars[key]+'"]').val();

    reg = '\\$\\{'+rVars[key].replace(/([(])/g,"\\(").replace(/([)])/g,"\\)")+'\\}';

    if(varVal != undefined) {
    data = data.replace(RegExp(reg,'g'),varVal);
    } else {
    data = data.replace(RegExp(reg,'g'),'');
    }
    }
    }
View Complete Thread