Skip to content
Advertisement

Effectively Search for set of substrings in a string Javascript

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

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

Let me know if there is even more effective way to do this than the above one.

Advertisement

Answer

Using Regex:

JavaScript

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement