convert array of words (strings) to regex and use it to get matches on a string

后端 未结 1 1500
甜味超标
甜味超标 2020-12-17 17:28

What is the most concise and efficient way to translate an array of strings in a regex and then use the regex multiple times on different strings to get the result matches a

相关标签:
1条回答
  • 2020-12-17 18:10

    Just join with pipeline, using Array.join

    var regexFromMyArray = new RegExp(myArray.join("|"), 'gi');
    

    and just do this as if condition is just redundant.

    for(var i = 0; i < matches.length; i++)
       console.log("Found:", matches[i]);
    
    1. A single method is being used instead of initial 3. (toString internally calls join(",")) and replace function is also not used.
    2. We have removed an unnecessary if-condition. So that's pretty quick.

    And since you talk about regexes, I'd like to say that

    1. A single regex initialization isn't going to cost you much.
    2. If your objective is really to match the words in the array, then just go with String.indexOf, which is a non-regex form of solving the same.
    0 讨论(0)
提交回复
热议问题