处理多个.search()参数的结果

时间:2014-07-20 16:34:40

标签: javascript search arguments

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无效,纯粹是出于示例目的。

1 个答案:

答案 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
    }
}