10

我需要检查一个字符串是否具有三个子字符串之一,如果是,则实现一个函数。我知道我可以使用检查一个子字符串,if (str.indexOf("term1") >= 0)但是有没有一种方法可以检查多个子字符串,而不是使用此代码的多个实例?

TIA

4

6 回答 6

27
if (/term1|term2|term3/.test("your string")) {
   //youre code
}
于 2013-03-04T12:49:19.903 回答
17

这可以动态而优雅地实现您想要做的事情

const terms = ["term1", "term2", "term3"]
const str = "very large string to check for term1, tern2, etc ..."

// check if the string has some of the terms
const result1 = terms.some(term => str.includes(term))

// check if the string has all the terms
const result2 = terms.every(term => str.includes(term))

这也使得为子字符串数组过滤字符串数组变得容易

const terms = ["term1", "term2", "term3"]
const strings = ["very large string text ....", "another large string text"] 

// filter the strings of the array that contain some of the substrings we're looking for
const result1 = strings.filter(str => terms.some(term => str.includes(term)))

// filter the strings of the array that contain all the substrings we're looking for
const result2 = strings.filter(str => terms.every(term => str.includes(term)))
于 2020-06-24T19:33:40.927 回答
10

你可以使用循环。甚至可以像这样创建一个辅助函数:

function ContainsAny(str, items){
    for(var i in items){
        var item = items[i];
        if (str.indexOf(item) > -1){
            return true;
        }

    }
    return false;
}

然后你可以这样调用:

if(ContainsAny(str, ["term1", "term2", "term3"])){
   //do something
}
于 2013-03-04T12:49:30.313 回答
3

也许是这样:

if (str.indexOf("term1") >= 0 || str.indexOf("term2") >= 0 || str.indexOf("term3") >= 0) 
{
 //your code
}
于 2013-03-04T12:48:53.793 回答
2

你可以做类似的事情

function isSubStringPresent(str){
    for(var i = 1; i < arguments.length; i++){
        if(str.indexOf(arguments[i]) > -1){
            return true;
        }
    }

    return false;
}

isSubStringPresent('mystring', 'term1', 'term2', ...)
于 2013-03-04T12:50:41.570 回答
2

.map()函数可用于将术语数组转换为布尔值数组,指示是否找到每个术语。然后检查是否有任何布尔值true.

给定一个数组terms

const terms = ['term1', 'term2', 'term3'];

true如果string包含以下任何内容,则此代码行将返回terms

terms.map((term) => string.includes(term)).includes(true);       

三个例子:

terms.map((term) => 'Got term2 here'.includes(term)).includes(true);       //true
terms.map((term) => 'Not here'.includes(term)).includes(true);             //false
terms.map((term) => 'Got term1 and term3'.includes(term)).includes(true);  //true

或者,如果你想将代码包装成一个可重用的hasTerm()函数:

const hasTerm = (string, terms) =>
   terms.map(term => string.includes(term)).includes(true);

hasTerm('Got term2 here', terms);       //true
hasTerm('Not here', terms);             //false
hasTerm('Got term1 and term3', terms);  //true

试试看:
https ://codepen.io/anon/pen/MzKZZQ?editors=0012

.map()文档:
https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

笔记:

  1. 该答案针对简单性和可读性进行了优化。如果需要非常大的术语数组,请使用一旦找到术语就会短路的循环。
  2. 为了支持 IE,transpile 以用声明替换出现的.includes(x)with.indexOf(x) !== -1=>with function
于 2018-11-08T08:26:30.963 回答