1
\$\begingroup\$

I'm looking for some JavaScript code improvement and optimization. Is it possible to optimize this block of code (for example, remove double array loop)?

replace: function(ex, str) {
    var arr = str.match(/{add_([A-Z]+)}/gi);
    if (arr && arr.length) {
       arr.each(function(e){            
          var id = e.replace('{add_','').replace('}',''),
          o = Core.get_data_by_id(ex.extensions, id);   

          if (o && o.status =="1") {
            str = str.replace('{add_'+id+'}', o.html);
          } 
       });
    } 

    var arr2 = str.match(/{banner_([0-9]+)}/gi);
    if (arr2 && arr2.length) {
       arr2.each(function(e){
         var id = e.replace('{banner_','').replace('}',''),
         b = Core.get_data_by_id(ex.banners, id);

         if (b && b.status =="1" && b.code && b.code.length) {
            var content = '<div class="units-row banner_'+b.id+'"><ul>' +
            b.code.each(function(s){
               content += '<li>'+s.code+'</li>';
            });                     
            content += '</ul></div>';
            str = str.replace('{banner_'+id+'}', content);
         } 
       });
    }

    return str;
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You should be using String.prototype.replace() with a function as the second argument. Example:

str = str.replace(/{add_([A-Z]+)}/gi, function(match, id) {
  var o = Core.get_data_by_id(ex.extensions, id);   
  return (o && o.status == "1") ? o.html : match;
}); 

str = str.replace(/{banner_([0-9]+)}/gi, function(match, id){
  var b = Core.get_data_by_id(ex.banners, id);

  if (b && b.status =="1" && b.code && b.code.length) {
    var content = '<div class="units-row banner_'+b.id+'"><ul>' +
    b.code.each(function(s){
       content += '<li>'+s.code+'</li>';
    });                     
    content += '</ul></div>';
    return content;
  } 
  return match; 
});

EDIT: I've added the second part.

\$\endgroup\$
4
  • \$\begingroup\$ But I will have two regular expressions: /{add_([A-Z]+)}/gi and /{banner_([0-9]+)}/gi \$\endgroup\$
    – XTRUST.ORG
    Jun 2, 2014 at 11:07
  • \$\begingroup\$ That was just an example. Your second regular expression is independent from the first one and can be replaced in a similar manner. \$\endgroup\$
    – RoToRa
    Jun 2, 2014 at 11:09
  • \$\begingroup\$ Thanks! Do you know how to combine 2 regular expressions and pass it to replace function? \$\endgroup\$
    – XTRUST.ORG
    Jun 2, 2014 at 11:19
  • \$\begingroup\$ I wouldn't do that. The functions a different enough to leave them separate, so leave the regular expressions separate, too. \$\endgroup\$
    – RoToRa
    Jun 2, 2014 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.