jquery / javascript检查多个子串的字符串

时间:2013-03-04 12:46:05

标签: javascript jquery string search

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

TIA

6 个答案:

答案 0 :(得分:9)

if (/term1|term2|term3/.test("your string")) {
   //youre code
}

答案 1 :(得分:8)

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

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
}

答案 2 :(得分:4)

这可以动态,优雅地实现您要尝试的操作

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

答案 3 :(得分:3)

也许这个:

if (str.indexOf("term1") >= 0 || str.indexOf("term2") >= 0 || str.indexOf("term3") >= 0) 
{
 //your code
}

答案 4 :(得分: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', ...)

答案 5 :(得分:0)

.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()函数中:

function hasTerm(string, terms) {
   function search(term) { return string.includes(term); }
   return terms.map(search).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,请进行转换以将.includes(x)的出现.indexOf(x) !== -1替换为=>的声明function
相关问题