Efficiently finding a group of substrings within a JavaScript string

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.

Answer №1

Utilizing Regular Expressions:

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

Important Information

This function will only retrieve the first fruit found in the string. For example, given the input "foobarapplebanana", it will return "apple". If you prefer to obtain an array of matching fruits like

[ "apple", "banana" ]
, then simply return match instead of match[0].

Test it out here

Answer №2

You can quickly verify these includes in a single line of code.

Start by setting up the list of available items, then proceed to check if the desired item is present. If not found, the default value will be returned.

const apple = "apple"
const banana = "banana"
const cherry = "cherry"
const dates = "dates"
const eggplant = "eggplant"
const defaultValue = "default"

let selectedFruit = "kiwi" // This value can change

const availableOptions = [apple, banana, cherry, dates, eggplant]

return availableOptions.includes(selectedFruit) ? selectedFruit : defaultValue;

Answer №3

If you're looking to filter an array based on a specific string, try utilizing the filter() method.

let searchString = "foobar" //This value can change
var matchingItems = items.filter(item => searchString.includes(item))
return matchingItems.length > 0 ? matchingItems[0] : "default"

Answer №4

A Straightforward Scenario

In situations where you only possess a few words, crafting a regular expression can be your solution - opt for either using match (refer to the accepted answer), or for simplicity's sake, simply extract the single word from the string:

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

Do bear in mind that this will identify the last occurrence of the word. While string.match() is usually preferable, I aim to respect @maksymiuk's approach. The efficiency advantage with regex lies in its ability to scan the string just once, seeking out all potential matches.

However, if we delve into optimization, let's dive into another scenario:

Hunting Down Multiple Words

In instances involving numerous search terms (such as an entire vocabulary) against a relatively brief text, a different strategy may prove more effective. Create a roster of available words and cross-reference them with an object containing the dictionary's entries 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', being the first encountered word

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

Is there a way to convert a PHP array into a JavaScript object and return it?

When I have an array defined and encode it using json_encode() $array = array("a" => "element1", "b" => "element2"); echo json_encode($array); The usual JSON output is: {"a":"element1","b":"element2"} However, my interest lies in getting this out ...

Having trouble fetching JSON data from a URL in my React Native project, the response is not as expected

getData() { return fetch("http://bitcfeedcms.rf.gd/script.php") .then(response => { console.log(response); response.json(); }) .then(responseJson => { this.setState({ data: responseJson }); }) .catch(error => { console.er ...

The navigation bar does not display the CSS when in the active state

I created a navigation bar in ReactJS and I need the tabs to stay highlighted when clicked, but the styles are not applying correctly. I have double-checked that the stylesheet is linked properly based on the Reactjs file structure. For reference, I used ...

attaching the model to chosen values rather than defining the chosen item

This is the coding I am currently using which is functioning correctly: <div class="col-md-12"> <div class="button-group"> <button type="button" class="btn btn-default btn-block btn-sm dropdown-toggle" data-toggle="dropdown"> ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

Rotate each row of the table in sequence with a pause between each flip

I have a table with 3 columns and 10 rows. I would like to flip each row one by one, where each row contains data on both the front and back sides. The flipping animation should be similar to the example provided in this link, but the flipping should sta ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Testing the seamless integration of Mocha, Node.js, and PostgreSQL

I have been struggling with this issue for quite some time now. After researching online and checking out various resources like the internet and StackOverflow, I couldn't find a solution that fits my requirements. To tackle the problem, I decided to ...

Adjusting canvas dimensions for angular chart.js: A quick guide

I am currently creating my first sample code using angular chart.js, but I am facing an issue with changing the custom height and width of my canvas. How can I adjust the height and width accordingly? CODE: CSS #myChart{ width:500px; he ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Using regular expressions, you can eliminate a specific segment of a string and substitute

Provide a string in the following format: lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone I am creating a function that will extract the specified address parts and remove any extra parts while maintaining maxim ...

Problem with JavaScript and Basic HTML5 Canvas

I'm trying to dive into learning about using a canvas, but I just can't seem to get this basic code to work. Does anyone know what I might be doing wrong? Link to jsfiddle <canvas id="ctx" width="500" height="500" style="border:1px solid #00 ...

Component inexplicably rendering multiple times

After encountering multiple re-renders in my code, I decided to comment out every line and discovered that the constant definition was causing the issue: const MyComponent = () => { console.log('render') // logs 4 times const myRef = useR ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...