简体   繁体   中英

Check if an array of strings contains a substring of a given string in javascript?

I have the following string:

var teststring = "Hello"

I have the following array of strings:

var listofstrings = ["Hellothere", "Welcome", "Helloworld", "Some String"];

I want to have inside of a conditional, a simple check to return if any thing in 'listofstrings' matches any part of 'teststring'. The following is the pseudocode:

if(teststring.indexOf(any-part-of-listofstrings) > -1)

How can I accomplish this? The simplest way I can think of is for looping it, but am looking to see if there is a better way.

By for looping, I mean multiple lines like:

for(var i = 0; i < listofstrings.length; i++) {
    if(teststring.indexOf(listofstrings[i] > -1) {
        return true;
    }
}

The above takes up multiple lines seems too complex for what I am trying to do...

You can use Array#some , and to make things shorter, use an arrow function and String#includes instead of String#indexOf :

if(listofstrings.some(str => teststring.includes(str))) {
    // found one
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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