简体   繁体   中英

How can I call this function only once yet loop as needed?

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 .

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).

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!"
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM