Hamidreza
Hamidreza

Reputation: 1915

How to search multiple variables in a string with the .search() method

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/);

Upvotes: 2

Views: 876

Answers (3)

Andy
Andy

Reputation: 63524

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

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

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

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

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

String.search(new RegExp(keyword1+'|'+keyword2));

Upvotes: 3

Related Questions