When looking to replace certain parts of a string, is it better to use the replace method directly or first check if there is a match and then perform the replacement?
var r1 = /"\+((:?[\w\.]+)(:?(:?\()(:?.*?)(:?\))|$){0,1})\+"/g;
arg = arg.replace(r1, function(outer, inner){
return eval(inner);
});
Alternatively, should I test for a match before replacing, like in the following code snippet?
var r1 = /"\+((:?[\w\.]+)(:?(:?\()(:?.*?)(:?\))|$){0,1})\+"/g;
if (r1.test(arg)) {
arg = arg.replace(r1, function(outer, inner){
return eval(inner);
});
}
The question ultimately revolves around understanding how the string.replace(regex, string) function works. Will it execute the callback even if there is no match, or simply return the original string? In that case, calling replace directly may be the way to go in order to avoid unnecessary matching by the regex engine.