Look for various smaller segments within a larger text

I am currently developing a digital library where each catalog "card" is represented by a specific string format:

'<div class="cardBox col-lg-4 col-md-6 col-sm-12"><div class="card" style="margin-bottom: 1em;"><img class="card-img-top" src="' + data.values[n][5] + '" alt="Card image cap"><div class="card-body"><h5 class="card-title">' + data.values[n][0] + '</h5><h6 class="doctype card-subtitle mb-2 text-muted">' + data.values[n][3] + '</h6><p class="card-text"><span class="font-weight-bold">Document Part #:</span> ' + data.values[n][1] + '<br /><span class="font-weight-bold">Rev:</span> ' + data.values[n][4] + '<br /><span class="font-weight-bold">Language:</span> <span class="language">' + data.values[n][10] + '</span><br /><span class="font-weight-bold">Customer:</span> <span class="customer">' + data.values[n][2] + '</span><br /><span class="font-weight-bold">Date Updated:</span> ' + data.values[n][11] + '</p><a href="' + data.values[n][7] + '" class="card-link" target="_blank">View Document</a><a href="' + data.values[n][6] + '" class="card-link" target="_blank">Download</a></div></div></div>'

There is also a search function that scans this string for the input entered into the search field. Here is the code snippet for the search functionality:

function searchByTitle() {
        var filter, card, title, i
        filter = document.getElementById("searchText").value.toUpperCase().split(" ");
        card = document.getElementById("content").getElementsByClassName("cardBox");
        console.log(filter);

        for (h = 0; h <= filter.length; h++) {
            for (i = 0; i < card.length; i++) {
                if (card[i].innerHTML.toUpperCase().includes(filter[h]) == true) {
                    card[i].style.display = "";
                } else {
                    card[i].style.display = "none";
                }
            }
        }
    }

However, there is an issue with the search functionality. When searching for multiple substrings separated by spaces, the documents matching all substrings must appear in sequential order within the card. If they do not appear in exact sequence, no relevant documents are displayed.

For instance, searching for: freezer widget thingy, will only display results if these terms are in exact order within the card content.

How can I modify the search function to find substrings in any random order within the larger string?

EDIT: I attempted to loop through both the text being searched and the array of search terms without success.

EDIT 2: I revised the looping logic as per the above suggestions, but now my search function does not return any results when typing into the search field. What could be causing this issue?

Answer №1

One alternative to consider is

card[i].innerHTML.toUpperCase().includes(...filter.split(' '))

Answer №2

If you're tackling a task like this, I recommend utilizing regular expressions:

if (searchText.match(/(^(?=.*freez)(?=.*widget).*$)/g)){
   card[i].style.display = ""; 
} else {
   card[i].style.display = "none";
}

This particular regex would successfully match variations such as:

freezer widget
widget freezer
freezer widget thingy

The (?=.*something) in this regex employs lookarounds, explained further at

To expand this regex for more search criteria, simply incorporate additional desired words:

/(^(?=.*freez)(?=.*widget)(?=.*deer)(?=.*warlock).*$)/g

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

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Identifying the specific area between two points on a chart by marking or highlighting

Recently, I had the opportunity to experiment with ANTS Performance Profiler for a few days and came across one of its standout features - the Interactive timeline. This feature allows users to select and highlight data between two points by simply moving ...

The labels on the bar graph ticks are failing to update in d3.js when the data is modified

My complete working code is below: const outerWidth = 600; const outerHeight = 300; const margin = 60; const height = outerHeight - 2*margin; const width = outerWidth - 2*margin; var data = [ { group: 'A', value: 5 }, { group: 'B', ...

Pressing the button element equipped with an event listener leads to the page being refreshed

I'm encountering an issue with my function in this JSFiddle window.addEventListener("load", init, false); function init() { let name = document.getElementById("name").addEventListener("blur", checkName, false); let startButton = document.getEl ...

When using Selenium WebDriver in Java, we noticed that despite initially failing with JavascriptExecutor, the element click method with WebElement performed successfully

Within the code snippet below, it is evident that using the WebElement.click() method successfully triggers an element, while the JavascriptExecutor.executeScript method encounters issues (although it works in most cases). WebElement e = driver.findElemen ...

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

Incorporate the latest value into an array of objects using JavaScript, taking into account its frequency

Hey there, I have an array of objects where I need to add a new property or value to each object based on its order number occurrence. For example, in the array of objects, there is a property called order number. If an object contains the highest order n ...

Utilize parameters in specified file in node.js

Currently, I am attempting to send variables to a file that I have imported in node.js in order to utilize them within that specific file. var myname = "Adnan"; var incfile = require('./ex.js'); My main goal is to access the myname variable wit ...

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...

Transform XLS files into JSON format seamlessly by leveraging the power of Sheetjs and FileReader.js

I have been attempting to transform an uploaded XLSX file into JSON format using https://github.com/bgrins/filereader.js for handling the upload process and https://github.com/SheetJS for the actual conversion of the file. Below is the code I am currently ...

The child outlet becomes empty after refreshing the URL with the ID sourced from the {{link-to}} method in Ember.js

I am facing a strange problem where the child outlet becomes empty every time I refresh the page with the id. I have a generated list using the {{link-to}} helper. <script type="text/x-handlebars" id="twod"> <div class="row"> ...

JavaScript interprets a null date as January 1, 1970

My current setup involves using AngularJS to call a web API and store data. However, an issue arises when JavaScript interprets a null date as January 1st, 1970 in the input box. Is there a way to display an empty input box when the date is null? When rea ...

Is there a way to interrupt a function in jquery before it completes its execution?

I've created a program that activates a sequence of 5 lights and sounds when a button is clicked, continuously looping through the sequence. There's another button labeled "cancel" to stop the loop midway and reset everything to the initial state ...

Accessing AngularJS variable scope outside of a function

Utilizing a socket, I am fetching data into an angularJS controller. $rootScope.list1= ''; socket.emit('ticker', symbol); socket.on('quote', function(data) { $rootScope.list1 = angular.fromJson(data.substring(3)); //I can ...

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

Encountered a "Transformer is not a constructor" error when trying to upgrade the React Native SDK version from 0.61.5 to 0.64

https://i.sstatic.net/LYdxj.pngRecently, I upgraded my react native version to the latest one and encountered an error stating "Transformer is not a constructor". The metro-react-native-babel-preset version I am currently using is 0.64.0. Can someone ple ...

Exploration of the contents within objects in JavaScript

Currently, I am conducting an experiment on login functionalities using Firebase. So far, I have succeeded in creating user accounts and storing additional information along with them. However, I am facing a challenge when it comes to retrieving this store ...

Including 'active' in an HTML button does not trigger the styles specified in the :active pseudo-class

When a button is clicked, I want its color to change. Below are the HTML elements in question: <div class='chatbot-container'> <div class='chatbot-wrapper' id='chatbot-wrapper' style="display:none;" & ...

Missing HTML elements when refreshing AngularJS page

I encountered a major issue with my simple Angular app. Whenever I refresh the page, all of the HTML content disappears! My problem is not related to Angular data or session/local storage, but only with the HTML itself. For instance, when I access the ...

Is your CPU overheating due to IE7, encountering script issues, and need help with debugging

My current web design project is running smoothly on all Mac browsers and Windows Firefox, Chrome, and IE 8. However, I'm facing significant issues with IE 7. Despite having the CSS almost in place with a few adjustments needed, the CPU usage spikes t ...