\$\begingroup\$
\$\endgroup\$
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;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 2, 2014 at 10:28
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
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.
answered Jun 2, 2014 at 11:06
-
\$\begingroup\$ But I will have two regular expressions: /{add_([A-Z]+)}/gi and /{banner_([0-9]+)}/gi \$\endgroup\$XTRUST.ORG– XTRUST.ORG2014年06月02日 11:07:33 +00:00Commented 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– RoToRa2014年06月02日 11:09:15 +00:00Commented 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– XTRUST.ORG2014年06月02日 11:19:09 +00:00Commented 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– RoToRa2014年06月02日 11:24:50 +00:00Commented Jun 2, 2014 at 11:24
default