Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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 and then iterate over them? Now I'm using the following:

var myArray = ['peaches', 'bananas', 'papaya', 'supercity'];
var myString = 'I want some papaya and some peaches';

var regexFromMyArray = new RegExp(myArray.toString().replace(/,/g, '|'), 'gi');

var matches = myString.match(regexFromMyArray) || [];

if (matches.length) {
  for (var i = 0, l = matches.length; i < l; i++) {
    console.log('Found: ' + matches[i]);
  }
}

performance is important here, so plain javascript please.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...