如How do you search multiple strings with the .search() Method?中所述,您可以在.search()
内使用多个参数。
但我如何知道.search()
中给出的哪些参数会返回正值?
E.g:
var search = string.search("hello|world|not");
if (search.positiveArgument == 1) {
//"hello" was found
} else if (search.positiveArgument == 2) {
//"world" was found
etc...
我知道.positiveArgument
无效,纯粹是出于示例目的。
答案 0 :(得分:1)
使用 .match()
代替正则表达式。匹配的部分将被退回。
例如:"yo world".match(/hello|world|not/);
返回["world"]
var search = str.match(/hello|world|not/);
if (search && search.length === 1) {
if(search[0] == "hello") {
// hello was found
}
else if(search[0] == "world") {
// world was found
}
else {
// not was found
}
}