jquery/javascript check string for multiple substrings

点点圈 提交于 2019-12-30 02:32:05

问题


I need to check if a string has one of three substrings, and if yes, to implement a 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?

TIA


回答1:


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



回答2:


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
}



回答3:


Maybe this:

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



回答4:


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



回答5:


The .map() function can be used to convert an array of terms into an array of booleans indicating if each term is found. Then check if any of the booleans are true.

Given an array of terms:

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

This line of code will return true if string contains any of the terms:

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:

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

.map() documentation:
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.


来源:https://stackoverflow.com/questions/15201939/jquery-javascript-check-string-for-multiple-substrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!