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:
JavaScript
x
22
22
1
const apple = "apple"
2
const banana = "banana"
3
const chickoo = "chickoo"
4
const dates = "dates"
5
const eggplant = "eggplant"
6
const default = "default"
7
8
let string = "foobar" // This String changes dynamically
9
if (string.includes(apple)){
10
return apple;
11
} else if (string.includes(banana)) {
12
return banana;
13
} else if (string.includes(chickoo)) {
14
return chickoo;
15
} else if (string.includes(dates)) {
16
return dates;
17
} else if (string.includes(eggplant)) {
18
return eggplant;
19
} else {
20
return default;
21
}
22
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:
JavaScript
1
9
1
const fruits = ["apple", "banana", "chickoo", "dates", "eggplant"];
2
let string = "foobar" //This is dynamic
3
for(let fruit in fruits) {
4
if(string.includes(fruits[fruit])){
5
return fruits[fruit];
6
}
7
}
8
return "default";
9
Let me know if there is even more effective way to do this than the above one.
Advertisement
Answer
Using Regex:
JavaScript
1
7
1
function matchFruit(input) {
2
const match = input.match(/apple|banana|chickoo|dates|eggplant|default/);
3
if(match)
4
return match[0];
5
return "default";
6
}
7
Note
this will only return the first matching fruit in the string. So "foobarapplebanana"
will return "apple"
. If instead you want to return an array of strings, [ "apple", "banana" ]
, then return match
instead of match[0]
.