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/);
1
  • What if they're both present? Search will only return the first one. Is that ok? Commented Sep 15, 2014 at 14:06

3 Answers 3

3

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

String.search(new RegExp(keyword1+'|'+keyword2));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.