Rolando
Rolando

Reputation: 62596

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

Upvotes: 1

Views: 87

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

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
}

Upvotes: 4

Related Questions