Compare and display the output of "what" plus the quantity

var str = "I hope ducks don't smile upon me whenever I pretend to be a duck!";
var matchAgainst = ['duck', 'smile', 'cows']

for (var ma = 0; ma < matchAgainst.length; ba++)
    if (str = matchAgainst.match(matchAgainst))
    {
    document.write
    }

Running low on ideas, so let me outline the problem that needs solving.

> Find a match in the "matchAgainst" array.
> If true, return

word = frequency(ascending order)

For example, given the line "I hope ducks don't smile upon me whenever I pretend to be a duck!", the desired output would be:

duck = 2
smile = 1

(No need to display 'cow = 0', it's unnecessary)

However, for the line "Today was not a good day", there should be no output.

Thank you.

Answer №1

Check out the code below for answers. It's important to familiarize yourself with the JavaScript regular expression object.

var str = "I wish cats wouldn't wink at me when I try to be a cat!";
var matchAgainst = ['cat', 'wink', 'dogs']

//Be consistent with the increment variable (changed from ba++)
for (var ma = 0; ma < matchAgainst.length; ma++) {
   //Create a global regex pattern to find all occurrences
   var rg = new RegExp(matchAgainst[ma], "g");

   //Search for matches and store them in an array
   var matches = str.match(rg);

   //If there are matches, display the count
   if(matches.length > 0) document.write(matchAgainst[ma] + ": " + matches.length + "<br>");
}

Answer №2

Currently, the output does not display the results in any specific order. However, I am working on implementing a sorting feature. Stay tuned!

let sentence = "I wonder if dolphins ever get tired of swimming all day long.";

let wordsToMatch = ['dolphins', 'swimming', 'tired'];

for (let wm = 0; wm < wordsToMatch.length; wm++)
{
    let regex = new RegExp(wordsToMatch[wm], 'g');
    let numOccurrences = sentence.match(regex).length;
    if (numOccurrences > 0)
        document.write(wordsToMatch[wm] + ' = ' + numOccurrences + '<br />');
}

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

Properly utilizing onpointermove for drawing in HTML5 Canvas: A guide

I have successfully implemented HTML5 Canvas Freehand drawing using onpointerdown, onpointerup, and onpointermove for mouse interactions. However, I am facing issues with mobile devices as it requires the addition of ontouchmove. Is there a way to utilize ...

Javascript has trouble processing data coming from an HTML input field

I am struggling to make my JavaScript code work with the input from my HTML input tag. The purpose of this program is for the user to input a number, and then the program will determine whether the number is positive, negative, or zero. Below is the code ...

My companion and I are facing a challenge with JavaScript and HTML - we are struggling to convert a button into a 3D model

(apologies for the language barrier, we are from Moscow and may not be very knowledgeable) We have encountered an issue: a question. My brother and I are attempting to create some code using HTML and JS to produce a 3D model with an interactive button that ...

mastering the nuances of jQuery event namespaces

Below are some code snippets to consider: $("#atc-button").bind("click.hctpAttach", function (e) { console.log("Add to cart button clicked.") }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...

Switching from a functional component to a class component in React

I need assistance converting a code snippet from using functional components with useEffect to a class component. Can someone please help me with this task? import * as React from "react"; export default class App extends React.Component { c ...

Convert CSV data into a dynamically allocated array of structures in accordance with ANSI 89 standards

I've been attempting to parse a csv file into a dynamically allocated array of structures, but unfortunately, I keep encountering a segmentation fault during the process. Below is the format of my data: SO02773202,5087001,0 SO02773203,5087001,0 SO02 ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Create a filter for a table using select and jQuery

I've been working on a select filter to update a table, and while it works perfectly for one select element, I'm encountering an issue when trying to use multiple select elements simultaneously. Here is the code snippet (also available in this J ...

Transforming data in javascript

I am faced with a data transformation challenge involving extracting information from user input in Apache Superset using metrics. The data is assigned to the variable dataTransformation. {country: "Afghanistan", region: "South Asia", y ...

When the mouse button is released or when an event listener is

I've been pondering a question that has yet to be fully answered. When I implement this technique to catch a mouse up event: <div onmouseup="/*Script to be executed*/"></div> Is it more efficient than this newer approach: <div id=" ...

What could be causing my React Router to fail in displaying the content of Home.js?

My <Route> is not functioning as expected The Route leading to the homepage does not show the content from the Home.js file import "./App.css"; import Navbar from "./components/Navbar"; import { BrowserRouter as Router, Route, Ro ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Check out the Pa11y JSON configuration file specifically designed for actions by visiting the following link: https://github.com/pa11y/pa11

Our automated accessibility testing is conducted using the Jenkins CI tool with the help of pa11y. Below is the Jenkinsfile used to execute these tests: node('mypod') { container('centos') { def NODEJS_HOME env.NODEJS_HOME = "${t ...

Automatically Submitting React Forms Using Code

Hey there! I'm having some trouble getting my form to submit inside the handleSubmit function in React. I need to prefetch some information before submitting the form, but I can't seem to trigger the submission once I'm done with my operatio ...

How come my h1 heading gets obstructed by the input box when the slideUp function is triggered

On my wikisearch page, I have a title and input box positioned around the middle of the page. When I click on the button, the title slides up along with the input box. However, the input box ends up covering the title completely. I'm trying to figure ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

Using identical generic types in both the @param and @returns sections of a function

Is there a way to use JSDoc comments to annotate a function that accepts and returns an object of the same type? For example, something like this: /** * Performs a task and returns an object of the same type * @param {T extends Object} src Source object ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...