I would like to check if a String exists in my array.
My Javascript Code :
if(Ressource.includes("Gold") === true )
{
alert('Gold is in my arrray');
}
So Ressource is my array and this array contains :
Ressource ["Gold 780","Platin 500"] // I printed it to check if it was true
I don't understand why my test if(Ressource.includes("Gold") === true don't work.
Best regards, I hope someone knows what is wrong with this.
-
4includes mathes the whole string not a part of itashish singh– ashish singh2018年09月15日 16:11:52 +00:00Commented Sep 15, 2018 at 16:11
-
hi @Adriani6 i already tryied this and it don't work to.user8834409– user88344092018年09月15日 16:16:45 +00:00Commented Sep 15, 2018 at 16:16
-
hello @ashishsingh there is no way to search only a world in my string ?user8834409– user88344092018年09月15日 16:18:29 +00:00Commented Sep 15, 2018 at 16:18
-
a direct method to achieve it , i am not aware. Indirectly, yes , you can refer the answers people have postedashish singh– ashish singh2018年09月15日 16:20:42 +00:00Commented Sep 15, 2018 at 16:20
4 Answers 4
The includes array method checks whether the string "Gold" is contained as an item in the array, not whether one of the array items contains the substring. You'd want to use some with the includes string method for that:
Ressources.some(res => res.includes("Gold"))
5 Comments
Gold? That would be Array#find instead of Array#some.item = Ressource.find(res => res.includes("Gold")) which will return either the first array item that contains "Gold" or undefined if the condition is never satisfiedYou should loop through your array until you find out if your value exist.
if (Ressource.some(x => x.includes("Gold") === true)) {
alert('Gold is in my arrray');
}
Your problem is that you have a number along with Gold in the string in your array. Try using regex like this:
var Ressource = ["Gold 232331","Iron 123"]
if(checkForGold(Ressource) === true ) {
console.log('Gold is in my array');
} else {
console.log('Gold is not in my array');
}
function checkForGold(arr) {
var regex = /Gold\s(\d+)/;
return arr.some(x=>{if(x.match(regex))return true});
}
The MDN docs have a excellent guide to regular expressions. Try this instead.
Comments
Another approach would be to use Array.prototype.find() and a simple RegExp. That would return the value of the element holding the search term. As said in most answers Array.prototype.includes() works if your search term matches exactly the array element Gold 780.
let Ressource = ["Gold 780","Platin 500"] ;
let found = Ressource.find(function(element) {
let re = new RegExp('Gold');
return element.match(re);
});
console.log(found);
// Working example of Array.prototype.includes()
if(Ressource.includes("Gold 780")) {
console.log('Gold is in my arrray');
}
Working Fiddle