Reputation: 1702
I have a Chrome extension that replaces certain phrases on webpages. It uses a 2 dimensional array. The [i][1] replaces the text in provided in the [i][0] value.
for (var i = 0; i < array.length; i++) {
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: array[i][0],
replace: array[i][1]
});
}
This code works fine yet it seems computationally expensive as it calls the findAndReplaceDOMText
function multiple times rather than just once. Is it possible to move the for loop inside the function to just wrap the find
and replace
params? If so what would that look like? I can only get console errors trying this.
Edit: The function traverses the DOM looking for all visible human readable text that contains the regex phrase provided at find
and replaces with the string provided at replace
.
Upvotes: 0
Views: 141
Reputation: 8506
Without modifying the function's behaviour, you can't. What you could do is separating the find and replace passes.
Your strings are stored in a kind of difficult to transverse way, so let's flat them out:
var flatFind = array.map(function(elem){
return elem[0]
})
var flatReplace = array.map(function(elem){
return elem[1]
})
Then, you'd need to create a regex string that encompasses all your search strings:
var searchString = "/("+flatFind.join("|")+")/g"
Then pass it to the function, using a function to find the index of the match:
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: searchString,
replace: function(portion, match){
var idx = flatFind.indexOf(match)
if(idx > -1) return flatReplace[idx]
else throw "hey, there's no replacement string for this!"
}
})
Upvotes: 1
Reputation: 4074
You could try to use the replace parameter as a function.
The find
-configuration-property then needs to be a regular expression (RegExp
-object) constructed of your search strings (like /first|second|third/g
). Do not forget the g
-modifier at the end.
As replace
-configuration-property you then create a function that checks which string occurred (you get that as the second parameter to your function). According to the match you then return the corresponding value (for example if match
is "first"
then you return "1st"
. If match
is "second"
then you return "2nd"
and so on).
Upvotes: 1