1

How do you check an array if a string contains the same text? Example, I have cards array that I declare and I want to find how many have the same string like clubs in my array. I tried using includes using jquery and it returns a boolean function true or false. What should be done here? Will it possible to use the find method in the array? Please help.

It should alert that an array has 3 strings that has the same value like clubs.

$(document).ready(function() {

var cards = ["ace_of_clubs.png","2_of_clubs.png","3_of_clubs.png","ace_of_hearts.png"];

var f_string = cards.includes("clubs");
alert(f_string);

});

1 Answer 1

2

You can use array#filter with string#includes to check for substring in your array of string.

var cards = ["ace_of_clubs.png","2_of_clubs.png","3_of_clubs.png","ace_of_hearts.png"],
    f_string = cards.filter(card => card.includes("clubs"));
console.log(f_string);

ES5 Code

var cards = ["ace_of_clubs.png", "2_of_clubs.png", "3_of_clubs.png", "ace_of_hearts.png"],
    f_string = cards.filter(function (card) {
    return card.includes("clubs");
});
console.log(f_string);

Sign up to request clarification or add additional context in comments.

2 Comments

How do I use f_string variable in an if condition sir @Hassan Imam do I freely use this if(f_string) to check how many string that has a substring of clubs?
In case you want to check for length, use f_string.length in your if condition.

Your Answer

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.