我找到了这个解决方案:How do you search multiple strings with the .search() Method?

但是我需要使用几个变量进行搜索,例如:

var String = 'Hire freelance programmers, web developers, designers, writers, data entry & more';
var keyword1 = 'freelance';
var keyword2 = 'web';
String.search(/keyword1|keyword2/);

最佳答案

您需要在正则表达式中使用字符串之前先对它们进行转义(除非您确定它们永远不会包含任何[|等字符),然后构建一个RegExp对象:

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

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


如果您有一系列搜索字词,则可以将其概括为:

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

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

String.search(re);

关于javascript - 如何使用.search()方法搜索字符串中的多个变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25849772/

10-11 22:11
查看更多