1

I wanted to loop through an array and check if a string exists in the array elements and my code below partially works. The problem is currently it logs the array element if a specified string exists anywhere in the array element but what I want to do is log if the string is in the array element but also the same index position. To explain this better say one of my array elements is testing and the string I'm looking for is tes because tes is occurring in the index position 0,1,2 the element logs. But say my array element is not testing and the string I'm looking for is tes it won't log because even though the string exists it's in the wrong index. How can I achieve this? Thanks in advance.

const myArray = ['test blah', 'this is test', 'testing 234', 'nothing']
const check = 'te'
for (var i = 0; i < myArray.length; i++) {
 if (myArray[i].includes(check)) {
 //should print myArray[0] and myarray[2]
 console.log(myArray[i]);
 }
}

dippas
60.9k15 gold badges125 silver badges134 bronze badges
asked Jul 18, 2022 at 21:22

1 Answer 1

3

You can use startsWith()

const myArray = ['test blah', 'this is test', 'testing 234', 'nothing']
const check = 'tes'
for (let i = 0; i < myArray.length; i++) {
 if (myArray[i].startsWith(check)) {
 console.log(myArray[i]);
 }
}

answered Jul 18, 2022 at 21:25
Sign up to request clarification or add additional context in comments.

Comments

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.