I’m writing a piece of code in JavaScript that is supposed to replace all the occurrences of a char in multiple strings inside a JSON obj.
Not all of the strings contain the specific char, and we are talking about a lot of strings. So my question is: When talking about efficiency, is it best to make the replace or to search the string for the char and only if found make replace?
In other words:
var obj = ["str","str2","tr3","str","tr2","str3","str","s22tr2","str3","st","rtr2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3"];
option 1:
for(var i=0;i<obj.length;i++){
if(obj[i].indexOf("s")!=-1){
document.write(obj[i].replace(/s/gi,"*"));
}
}
option 2:
for(var i=0;i<obj.length;i++){
document.write(obj[i].replace(/s/gi,"*"));
}
Thoughts?
Thanks.
It depends on the number of elements in the obj and the size of each element with direct replace faster in most cases. What is by far the fastest for the sample you provided is “join and replace”. Check this very lazy example:
Note: ‘|’ represents a char (or even a tag) that is not included in the object elements and helps to avoid errors.
Pick and choose.
UPDATE:
Added capital S in 1st test.
Interesting case to explore: /s/gi.test vs indexOf