I currently have a string and set of substrings/search strings which I want to effectively search in the given string. This is what I have currently:
const apple = "apple"
const banana = "banana"
const chickoo = "chickoo"
const dates = "dates"
const eggplant = "eggplant"
const default = "default"
let string = "foobar" // This String changes dynamically
if (string.includes(apple)){
return apple;
} else if (string.includes(banana)) {
return banana;
} else if (string.includes(chickoo)) {
return chickoo;
} else if (string.includes(dates)) {
return dates;
} else if (string.includes(eggplant)) {
return eggplant;
} else {
return default;
}
This approach works, however I am looking for a more compact and efficent way of searching for substrings in a given string.
Edit: I am currently using the following way:
const fruits = ["apple", "banana", "chickoo", "dates", "eggplant"];
let string = "foobar" //This is dynamic
for(let fruit in fruits) {
if(string.includes(fruits[fruit])){
return fruits[fruit];
}
}
return "default";
Let me know if there is even more effective way to do this than the above one.
return fruits.find(f => string.includes(fruit));