Locating numerous words within a given string

In my quest to identify specific words within a comma-separated log, I have encountered an issue. The current code snippet effectively locates individual words, but struggles to find all three words together in the log.

$log = "Left Side Turn, Left Side Road, No Turn, Left, Right Turn";
var currLog = $("#log").text();

var theName = "Left Side Road";      //target phrase...

var currLogWords = currLog.split(/\b/);
        var hits = [];
        for (var i = 0; i < currlogWords.length; i++) {
            if (theName == currlogWords[i]) {
                hits.push(currlogWords[i]);
            }
        if (hits == 0) { do something } else { do other }

Answer №1

Your current code has a typo with currLogWords written as currlogWords, so it will likely result in an error like currlogWords is not defined.

To search for the complete string, you can try the following:

var log = "Left Side Turn, Left Side Road, No Turn, Left, Right Turn";
    var currLog = $("#log").text();

    var theName = "Left Side Road";      //this is the target string to search for...

    var currLogWords = log.split(',');
            var hits = [];
            for (var i = 0; i < currLogWords.length; i++) {
                if (theName.trim() == currLogWords[i].trim()) {
                    hits.push(currLogWords[i]);
                }
            }
            if (hits == 0) { 
                console.log(hits.length); 
                } else { 
                    console.log(hits);
                    console.log(hits.length); 
                }

Answer №2

When utilizing the split() function, the parameter specified determines how the string's content will be divided. Instead of currently using \b to split at any word break (such as a space), consider changing it to a comma to exclusively divide the string at commas. It is also important to eliminate leading and trailing whitespaces after splitting to remove any additional whitespace around each item separated by a comma.

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

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

Translation of country codes into the complete names of countries

Currently, my code is utilizing the ipinfo.io library to retrieve the user's country information successfully. This is the snippet of code I am using to fetch the data: $.get("https://ipinfo.io?token=0000000000", function(response) { console.log ...

AngularJS ng-repeat to create a series of radio button options

This particular snippet of code generates two sets of radio buttons. The first set consists of individual radio buttons, while the second set is dynamically created using ng-repeat. Users can select any of the radio buttons by clicking on them directly or ...

What is the best way to implement a user-customizable dynamic URL that incorporates API-generated content in a NextJS and React application?

Seeking assistance with implementing customizable dynamic URLs in Next.js with React. My current project involves a Next.js+React application that uses a custom server.js for routing and handling 'static' dynamic URLs. The goal now is to transiti ...

Issue with Laravel ReactJs: My changes in the ReactJs file are not being reflected on the website

I've been utilizing Reactjs within Laravel. Recently, I made some modifications to my React Component and upon refreshing my browser, the changes did not reflect. Here are the files involved: resources/views/welcome.blade.php <!doctype html&g ...

Contrast between the act of passing arguments and using apply with arguments

I have an important backbone collection that utilizes a save mixin to perform Bulk save operations (as Backbone does not natively support this feature). // Example usage of Cars collection define([ 'Car', 'BulkSave' ], function(Car ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

Seeking advice on removing the initial blank space from a dropdown value in Angular.js

I have a deeply thought-out logic that I would like to illustrate with an example. However, in order to present it effectively, I am looking for suggestions on how to simplify the process without relying too heavily on the controller. <select class="fo ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Experiencing pagination problems with Vue / Laravel framework

Trying to implement pagination for fetched data in a Vue project, but encountering an issue: New Question Error encountered during rendering: "TypeError: this.estates.filter is not a function" Am I overlooking something here? Pagination.vue ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

JQuery unable to recognize dynamically inserted Anchor Tag through AJAX request

I am currently working on a page that is sourcing a large amount of data from a database through various PHP files. To achieve this, I am using JQuery to identify specific events and trigger AJAX requests to the necessary PHP file to display the required c ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

Passing object attributes to a modal in AngularJS

I am trying to figure out how to pass a complete object to my modal so that I can view all of its attributes there. Currently, the items I have look like this: $scope.items = [{ Title: title, Id: id }] On my html page, I am using 'ng-repeat' as ...

Error message: When using the Semantic UI React Modal, the Portal.render() function requires a valid React element to be returned, otherwise

Currently, I am working on integrating the Semantic UI React modal into my dashboard application built using React. To facilitate this integration, I have developed a ModalManager component that will be utilized in conjunction with Redux to handle the stat ...

"Encountering a 400 Error While Attempting to Edit Requests in NodeJS/A

Currently, I am building an application using Ionic/Angular with a NodeJS backend. Within this project, I have created an update form that allows users to modify or delete a specific row. While the deletion function is working fine, I am facing some challe ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

Prevent specific fields from being saved in Node MongoDB native

When working with MongoDB and using the node mongodb native driver to insert documents, I have encountered an issue. The objects I am inserting have fields that I do not want to be saved in the database: var x = { field: 'value', _nonPersist ...

HTML elements not displaying in Ajax form

I am encountering an issue with my ajax based feedback form where the form is displaying the html from the response instead of processing it correctly. Here is the JQuery code: $(document).ready(function() { var form_holder = $('#form-holder'); ...

Using Node.js to render when a task has been completed

I am currently developing a Node.js Application using Express.js. One of the challenges I face is rendering data from another site on a page using Cheerio.js. While this in itself is not an issue, I struggle with determining how to render the data once the ...