2

I fount this solution: How do you search multiple strings with the .search() Method?

But i need to search using several variables, For example:

var String = 'Hire freelance programmers, web developers, designers, writers, data entry & more';
var keyword1 = 'freelance';
var keyword2 = 'web';
String.search(/keyword1|keyword2/);
Community
  • 1
  • 1
Hamidreza
  • 1,825
  • 4
  • 29
  • 40

3 Answers3

3

You can compose the regex with the RegExp constructor instead of a literal.

String.search(new RegExp(keyword1+'|'+keyword2));
Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

You'll want to escape the strings before using them in the regular expression (unless you're certain they'll never contain any [, |, etc. chars), then build a RegExp object:

function escapeRegExp(string){
  return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}

var re = new RegExp( escapeRegExp(keyword1) + "|" + escapeRegExp(keyword2) );
String.search(re);

If you have an array of search terms, you could generalize this:

var keywords = [ 'one', 'two', 'three[]' ];

var re = new RegExp(
  keywords.map(escapeRegExp).join('|')    // three[] will be escaped to three\[\]
);

String.search(re);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • You can't, unless you're certain of the *order* of the keywords. If you're looking for all those keywords in any order, you'd need to search for each string in turn. – Paul Roub Sep 15 '14 at 18:50
0

search will only return the index of the first match, it won't search any further. If you wanted to find the indexes for all the keywords you can use exec instead:

var myRe = new RegExp(keyword1 + '|' + keyword2, 'g')
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = "Found " + myArray[0] + " at position " + myArray.index;
  console.log(msg);
}

OUTPUT

Found freelance at position 5

Found web at position 28

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95