Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript.

var title = "Discovering the Best Book of All Time";
var search1 = "of DiscoverinG boOk Best"; 
var search2 = "Of TIme best all"
var search3 = "Book discovering time"

When using indexOf(), it only indicates that search1 is false, while search2 and search3 are true because the words may not be in correct order or clumped together. What approach should I take to create a search algorithm that identifies such cases?

Answer №1

If you're looking for a way to determine if all the words in the search query exist within the target text, regardless of case or word boundaries, then this function is for you.

function checkWords(data, target) {
    var words = data.toUpperCase().split(/\s/);
    if (words.length === 0) {return(false);}
    var uTarget = target.toUpperCase().replace(/\s/, "");
    var matchCount = 0;
    for (var i = 0; i < words.length; i++) {
        if (uTarget.indexOf(words[i]) != -1) {
            ++matchCount;
        }
    }
    return(matchCount === words.length);
}

Keep in mind that this algorithm doesn't consider word boundaries, so searching for "an" would match with words like "and" or "answer". Adding support for word boundaries would require additional code to identify what constitutes a valid boundary between words.

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

Navigating through a sequence of URLs in Node.js, one by one

I am new to node js and experimenting with creating a web scraping script. I've received permission from the site admin to scrape their products as long as I make less than 15 requests per minute. Initially, my script was requesting all URLs at once, ...

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

The jQuery draggable feature ceases to function after it has been dropped

I have a scenario with two divs, each housing a list of quantities and items. These items are draggable, and the div containing them is droppable. The condition here is if an item with the same name exists in the div, it cannot be dropped on that div again ...

How is the purpose of nesting functions within functions achieved in nodejs?

Take a look at this example: var tools1 = require('../tools/tools1'); var test_func = function(arg1, arg2, arg3) { var local_var_1 = "lc1"; var local_var_2 = "lc2"; return function(data) { var result = tools1.doSth(local_va ...

Exploring jQuery AJAX Attributes during ajaxStart and ajaxStop event handlers

With my project consisting of over 40 ajax webservice calls, I am looking to incorporate additional debugging features. One such feature is a timing method which I have already developed using my Timer class/object in Javascript. I'm seeking assistan ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

"Exploring ways to create and save content in a different root folder within a nodejs project using my

In the process of developing my npm module, I am faced with the task of creating or writing a file in either the root directory or a specific folder within the nodejs project that will be utilizing my module. This includes users who will be implementing my ...

Avoid matching the regular expression

Currently, I am utilizing the regular expression /\s*?left:\s*?-?\d+\.?\d*px;/im to search for instances like: left: 100.5px;. An issue that I am encountering is that it also detects margin-left: 100px; or padding-left.... My obje ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Obscure Promise Structure - Accomplish, Flop, Achieved

I came across the following code block and I'm struggling to understand it. While I have a good grasp on promises in the context of: deferred.then(successCb, errorCb); This code snippet appears to have three callbacks (complete, fail, done>) whic ...

Having trouble getting this JavaScript query to function properly

The initial div in the code snippet below showcases the name of a university. When this name is clicked, it activates the function display_people(). This function is responsible for displaying or hiding the individuals associated with that university. The ...

What is the best way to retrieve a complete DynamoDB scan response using aws-sdk-js-v3 without object types included in the marshaled response?

After struggling with the AWS JS SDK V3 documentation and examples, I decided to share my findings to help others. The official SDK docs were frustrating and misleading, especially when it came to showing marshaled output properly. While the DDB Doc client ...

Can we incorporate modulo into the loop?

I have a JavaScript function with HTML code inside. I need the ".one-card" div to repeat four times within each ".row" div. The ".row" div is being repeated in a foreach loop. I want to check if the result of modulo (4) is not equal to zero, then display t ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Guidelines for deploying a node.js REST API application successfully in a production environment

As I venture into the world of node.js apps, I find myself faced with a dilemma. I've created a REST API using node.js that functions perfectly on my local machine. However, when I attempt to build it using webpack, I'm uncertain about how to run ...