简体   繁体   English

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

[英]jquery/javascript check string for multiple substrings

I need to check if a string has one of three substrings, and if yes, to implement a function.我需要检查一个字符串是否具有三个子字符串之一,如果是,则实现 function。 I know I can check for one substring using if (str.indexOf("term1") >= 0) but is there a way to check for multiple substrings short of using several instances of this code?我知道我可以使用if (str.indexOf("term1") >= 0)检查一个 substring 但是有没有办法检查多个子字符串,而不是使用这个代码的几个实例?

TIA TIA

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

This achieves dynamically and elegantly what you are trying to do这可以动态而优雅地实现您想要做的事情

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

This also makes it easy to filter an array of strings for an array of substrings这也使得为子字符串数组过滤字符串数组变得容易

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

You could use a loop.你可以使用循环。 Maybe even create a helper function like so:甚至可以像这样创建一个辅助函数:

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

    }
    return false;
}

Which you can then call like so:然后你可以这样调用:

if(ContainsAny(str, ["term1", "term2", "term3"])){
   //do something
}

Maybe this:也许这个:

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

You can do something like你可以做类似的事情

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', ...)

The .map() function can be used to convert an array of terms into an array of booleans indicating if each term is found. .map()函数可用于将术语数组转换为布尔值数组,指示是否找到了每个术语。 Then check if any of the booleans are true .然后检查是否有任何布尔值true

Given an array of terms :给定一组terms

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

This line of code will return true if string contains any of the terms :如果string包含任何terms这行代码将返回true

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

Three examples:三个例子:

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

Or, if you want to wrap the code up into a reusable hasTerm() function:或者,如果您想将代码包装成一个可重用的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

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

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

Notes:笔记:

  1. This answer optimizes for simplicity and readability.这个答案优化了简单性和可读性。 If extremely large arrays of terms are expected, use a loop that short-circuits once a term is found.如果预期有非常大的项数组,请使用一旦找到项就短路的循环。
  2. To support IE, transpile to replace occurrences of .includes(x) with .indexOf(x) !== -1 and => with a function declaration.为了支持 IE,转译以用.indexOf(x) !== -1=>替换出现的.includes(x)function声明。

If you want to check for multiple string matches and highlight them, this code snippet works.如果您想检查多个字符串匹配并突出显示它们,则此代码段有效。

function highlightMatch(text, matchString) {
    let textArr = text.split(' ');
    let returnArr = [];
    
    for(let i=0; i<textArr.length; i++) {
        let subStrMatch = textArr[i].toLowerCase().indexOf(matchString.toLowerCase());
        
        if(subStrMatch !== -1) {
            let subStr = textArr[i].split('');
            let subStrReturn = [];
            
            for(let j=0 ;j<subStr.length; j++) {
                
                if(j === subStrMatch) {
                    subStrReturn.push('<strong>' + subStr[j]);    
                } else if (j === subStrMatch + (matchString.length-1)){
                    subStrReturn.push(subStr[j] + '<strong>');
                } else {
                    subStrReturn.push(subStr[j]);
                }
            }
            returnArr.push(subStrReturn.join(''));
        } else {
            returnArr.push(textArr[i]);
        }
    }
    return returnArr;
}


highlightMatch('Multi Test returns multiple results', 'multi'); 
=>  (5) ['<strong>Multi<strong>', 'Test', 'returns', '<strong>multi<strong>ple', 'results']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM