0

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.

3
  • 2
    search/match for the regular expression: /(apple)|(banana)|(chickoo)|(dates)|(eggplant)|(default)/g Commented Feb 2, 2022 at 16:37
  • 1
    It looks to me like a find... return fruits.find(f => string.includes(fruit)); Commented Feb 2, 2022 at 16:55
  • Define effective? Less code / more performant / something else? Commented Feb 2, 2022 at 16:55

4 Answers 4

2

Using Regex:

function matchFruit(input) {
    const match = input.match(/apple|banana|chickoo|dates|eggplant|default/);
    if(match)
        return match[0];
    return "default";
}

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].

Test Here

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

4 Comments

This is actually better than the replace I did
This seems to be super ccol. But I had one doubt, what is faster: RegEx match or String finds(includes or filter)?
@Dext1232 you'd just have to test and benchmark for yourself. But what I can tell you is that Regex would provide you a forward-only search. Whereas if you did a String.includes for each fruit, it would have to re-iterate the entire string for each fruit you search for.
Regex beats search-over-and-over approach because it only looks for the whole stuff in one round.
1

You can use filter()

let string = "foobar" //This is dynamic
var matchingFruits =  fruits.filter(fruit=>string.includes(fruit))
return matchingFruit.length>0?matchingFruit[0]:"default"

2 Comments

may as well just use find which does the same without having to check the length of an array
Yes right this is just if you need to find all the elements which are included in string.
0

You can check these includes in one line.

First you have to create the available list and then check it. If it was not found in the list, default is returned.

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

const availableFruits = [apple, banana, chickoo, dates, egplant]

return availableFruits.includes(string) ? string : default;

1 Comment

I think the OP is checking the other way round: does string contain any of the fruits
-1

Simple case

If you only have a couple of words, you can compose a regular expression - either go with match (see accepted answer), or if you go for simplicity, you can even just reduce the whole string to the word found inside:

found = string.replace(/.*(apple|banana|cherry).*/,"$1")

This will find the last one, btw. Again, string.match() is better, I just don't want to steal @maksymiuk's solution. Regex is faster than multiple straight searches because it only iterates over the string once, looking for all possible candidates.

Now if we're optimizing, let's consider another case:

Look for many words

If there are many search strings (like a whole dictionary) and you only have a relatively short text, a reverse approach could be more efficient. Build a list of words you have, and check them against an object that has the dictionary words as keys.

function searchManyWordsInText(text,wordList) {
    let wordLookup = {};
    for(let w of wordList) wordLookup[w] = 1;
    let textWords = text.split(/\s+/);
    for(let x of textWords) if(wordLookup[x]) return x;
    return false;
}

//  test it:

searchManyWordsInText(
    'this is a banana championship',
    ['apple','banana','cherry']
);

//  returns 'banana', the first word found

1 Comment

I'm amazed by people who downvote everyone else just to be on top of the list.

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.