I am currently working on a method to efficiently search for specific substrings within a given string. Here is my current implementation:
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;
}
While this approach is functional, I am seeking a more concise and effective way of conducting substring searches within a given string.
Edit: The updated version of my code looks like this:
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";
If you have any suggestions for further improving the efficiency of this process, please let me know.