1

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

ibrahim mahrir
31.8k5 gold badges50 silver badges78 bronze badges
asked May 6, 2018 at 16:12
3
  • 1
    @Dan that question does not address my question. The answer in that question requires an exact match to the entire string. If you modified the example in answer to ["I", "like", "turtles love me"], then it breaks and returns false. I want to return true in that case because turtles was part of the substring of at least one of the items in the array. Commented May 6, 2018 at 16:16
  • This is not built into JavaScript. You will have to write a function to do this yourself. Commented May 6, 2018 at 16:20
  • The question is not a duplicate of the suggested link. Please don't vote to close. Commented May 6, 2018 at 16:24

1 Answer 1

4

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
}
answered May 6, 2018 at 16:20
1
  • 1
    This is shorter and less complex than a for loop for sure. If anyone has even better/shorter ways of doing this, please share. Perhaps someday, Javascript will have some built in function to handle this. Commented May 6, 2018 at 17:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.