Reputation: 1915
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
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
Upvotes: 0
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
Reputation: 33399
You can compose the regex with the RegExp
constructor instead of a literal.
String.search(new RegExp(keyword1+'|'+keyword2));
Upvotes: 3