JavaScript - identifying specified tags within a given string

I have created an array containing some tags:

var myArray = [
    "mouse",
    "common",
    "malcom",
    "mountain",
    "melon",
    "table"
];

Now, I need to extract these defined tags from a given string. For instance,

from the string: the mouse is on the desk, I want to extract the "mouse" tag

or from the string the mouse is on the table, I aim to extract both "mouse" and "table" tags.

The code I've implemented serves this purpose partially, but there seems to be an issue:

var myArray = [
    "mouse",
    "common",
    "malcom",
    "mountain",
    "melon",
    "table"
];

Object.defineProperty(Array.prototype, "MatchInArray", {
    enumerable: false,
    value: function(value) {
        return this.filter(function(currentItem) {
            return currentItem.match(value);
        });
    }
});

function doSearch(text){
    out = myArray.filter(function(currentItem){
        return currentItem.toLowerCase().indexOf(text) !== -1;
    });
    return out;
}

myInput.oninput = function(){
    var XXX = this.value;
    var YYY = XXX.replace(/ /g,',');
    var ZZZ = YYY.split(',');
    for(var i=0; i<ZZZ.length; i++){
        output.innerHTML = doSearch(ZZZ[i]);
    }
    //output.innerHTML = doSearch(this.value);
};

What am I doing wrong?

DEMO

Answer №1

Reverse the text-to-item comparison to avoid extensive regex and splitting:

function searchItems(item){
    results = myArray.filter(function(text){
        return item.toLowerCase().indexOf(text) !== -1;
    });
    return results;
}

userInput.oninput = function(){
    resultDisplay.innerHTML = searchItems(this.value);
};

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

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

Troubleshooting problems with mouseover, mouseout, and a dropdown menu in Ext 4

Here's the issue I'm facing: I have a menu that needs to hide and show elements as the mouse passes by. I've managed to achieve this with mouseover and mouseout events, but the problem is that I can't select an item from the dropdown m ...

Scroll through like Uber Eats with horizontal ScrollSpy and navigation arrows

I am in need of a menu style similar to Uber Eats, with an auto horizontal scroll feature for categories that exceed the available width. Additionally, I would like the active links in the menu to change as the user scrolls down, reflecting the current cat ...

Differences between AsyncData and nuxtServerInit

I currently have cookies set up for authorization user and user token. On each nuxtServerInit, I check the cookies for the same data and save them to the store. However, when using asyncData on certain pages, it seems like the asyncData function runs bef ...

Is there a way to conceal the parent div when all of its child divs are hidden?

I have a series of dynamically created divs set up like this: <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> < ...

JavaScript array reformatting executed

I have an array object structured like this. [ {student_code: "BBB-002-XRqt", questions: "Length (in inches)", answer: "8953746", time: "00:00:08:15"}, {student_code: "CCC-003-TYr9", questions: "He ...

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Whenever I utilize axios, I encounter the issue 'Request failed with status code 400'

I'm encountering an issue while trying to implement a registration action through axios. Whenever I attempt to submit the form, I receive the error message "Request failed with status code 400." I am unsure of what mistake I may have made in my code. ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

How can I use a mouse scroll wheel to activate the "hover" event using Javascript?

Is there a way to change the default behavior where using the mousewheel to scroll down the page does not trigger any hover events? I want the hover event to be triggered even if the pointer is hovering over a div and regardless of whether the user used th ...

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...

Choose all options within the optgroup group

I am facing an issue with a select element that contains grouped options. My requirement is to be able to select or deselect all options within an optgroup when a specific option is clicked. Furthermore, I need the functionality to allow multiple optgroups ...

Show a checkbox element with a square in the center instead of a tick mark

Is there a way to create a custom checkbox in HTML with a black box in the center, similar to the third checkbox shown in the image below? I've noticed this design in many interfaces, but I haven't been able to find a satisfactory example online ...

Node.Js error: "The requested resource does not have the 'Access-Control-Allow-Origin' header present."

This particular query shares similarities with others, however there is a perplexing difference that is causing it to malfunction. Previously, my JavaScript was able to fetch 6 json files without any issues. In Node.JS, I have configured cors and headers ...

Learn how to implement pagination in your React Native app by utilizing the orderByChild, equalTo, and endBefore functions in a Firebase

I am currently developing a pagination feature that loads more data based on category type. However, I have encountered an issue: endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo). I understand that I can't ...

Communication between Nodemailer and Mailgun

I keep encountering an authentication issue while trying to use Nodemailer with Mailgun. I followed the Nodemailer documentation which states compatibility with Mailgun SMTP, but unfortunately, I am consistently facing this error when executing my applicat ...

Utilizing an Angular Service within a method, embedded in a class, nested inside a module

module Helper { export class ListController { static handleBatchDelete(data) { // Implementing $http functionality within Angular ... $http.post(data) } } } // Trigger on button click Helper.ListController. ...

Eliminate any unauthorized characters from the email address

My goal is to assist users in avoiding entering invalid characters in an email input field (prior to server-side validation and cleanup). Please note: I am not validating emails on the frontend, only cleaning them up. // Coffeescript $(Element).find(&apo ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...