Discover the shared word frequencies between two string variables

Let's consider having two strings that look something like this

var tester = "hello I have to ask you a doubt";
var case   = "hello better explain me the doubt";

In this scenario, both strings contain common words such as hello and doubt. Let's assume the default string is tester, and we have another variable called case which holds a set of words. The objective is to determine the count of common words present in both tester and case, returning the result in the form of an object.

Desired Result

{"hello" : 1, "doubt" : 1};

The current implementation approach is outlined below

var tester = "hello I have to ask you a doubt";
function getMeRepeatedWordsDetails(case){
    var defaultWords = tester.split(" ");
    var testWords    = case.split(" "), result = {};
    for(var testWord in testWords){
        for(var defaultWord in defaultWords){
            if(defaultWord == testWord){
                result[testWord] = (!result[testWord]) ? 1 : (result[testWord] + 1);  
            }
        }
    }
    return result;
}

I am considering whether Regex may offer a more efficient way to accomplish this task by identifying pattern matches. Your feedback on whether my current approach is correct or if utilizing Regex would be beneficial is appreciated.

Answer №1

To effectively split the string called tester into individual words, you can utilize a regular expression as a tokenizer. This tokenizer will break down the string and create a list of words. You can then construct a second regular expression using this word list to identify matching words within a given sentence. Here is an example:

var tester = "a string with a lot of words";

function findRepeatedWords ( sentence ) {
  sentence = sentence + " ";
  var regex = /[^\s]+/g;
  var wordListRegex = new RegExp ( "(" + tester.match ( regex ).join ( "|" ) + ")\\W", "g" );
  matchWords = sentence.match ( wordListRegex );
  var words = {};
  
    for ( var i = 0; i < matchWords.length; i++ ) {
      var matchWord = matchWords [ i ].replace ( /\W/g, "" );
      var word = words [ matchWord ];
      
        if ( ! word )
          words [ matchWord ] = 1;
        else
          words [ matchWord ]++;
    }   
  return words;
} 

console.log ( findRepeatedWords ( "another string with some words" ) );

The key line for tokenizing the string is:

var regex = /[^\s]+/g;

When you run:

tester.match ( regex )

You will obtain a list of words from the tester string:

[ "a", "string", "with", "a", "lot", "of", "words" ]

This array is used to create a second regular expression that identifies all these words; wordListRegex follows this pattern:

/(a|string|with|a|lot|of|words)\W/g

The addition of \W ensures only complete words are matched. Without it, the letter a would match any word starting with 'a'. The result of applying wordListRegex to sentence produces another array containing words found in both tester and sentence. The subsequent for loop tallies the occurrences of each word in the matchWords array, ultimately generating the desired output object.

Please note:

  • Ensure a space is added at the end of sentence to allow \W in wordListRegex to capture the last word: sentence = sentence + " "
  • Eliminate any extraneous characters captured by \W during matching:
    matchWord = matchWords [ i ].replace ( /\W/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

Add multiple images to various div containers

I am facing a challenge with my code as I am trying to upload and display two different files inside of two different divs using two buttons. Currently, my code is only working for one image. How can I modify the code to handle two images successfully? Any ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...

Unable to send an API request from Postman to a database through express and mongoose technology

This is my server.js: const express= require('express'); const app = express(); // const mongoose= require('mongoose'); // load config from env file require("dotenv").config(); const PORT = process.env.PORT || 4000; // middl ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Substitute the website address using regular expressions

Looking to update the iframe URL by changing autoplay=1 to autoplay=0 using regular expressions. jQuery(document).ready(function($){ $('.playButton').click(function(){ $('.flex-active-slide iframe').contents().f ...

What is the best time to fetch the height of an element containing an image?

I am working on my web app and I want to implement a popup element that contains an <img> element. Typically, the image source is larger than necessary, so I resize it using CSS. However, before displaying the popup, I need to determine its outerHeig ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

"Revamping data structures with Redux, organized entities, and advanced merging techniques

Currently, my setup involves Redux, React, and Lodash working together to manage a normalized entities store. The challenge I'm facing is that whenever I incorporate new entities into a redux reducer using lodash's merge function, the references ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Using Vue to create a component that binds an array as its data source

Having trouble binding an array as a variable and accessing it in the child component, resulting in the variable being undefined. Is there a way to pass an array from a view to a component so that the component can use this array to create a child componen ...

PayPal's Intelligent Payment Buttons: Oops! There seems to be an issue with parsing the JSON data - an unexpected character was found at line 1,

I've been racking my brain over this issue for the past two days... I've been attempting to integrate Smart Payment Buttons from PayPal, diligently following each step in the guide. However, I keep encountering the following error: Error: JSON. ...

Having trouble with your UI Router states not updating correctly when changing the URL in your Angular UI Router?

I have tried numerous solutions and tutorials already with no success in finding the right answer. Therefore, I am posting here in hopes of receiving a fresh perspective and a little challenge. Using: angular ui router The Issue I have set up differen ...

What is the best way to continuously click a JavaScript link until it disappears?

Many websites utilize single-page pagination to display more content with each click. It can be beneficial to view all the content on one page, such as for web crawling purposes. Much like automatically clicking a button using Greasemonkey, how can JavaScr ...

Using Mapbox GL JS to Showcase Latitude and Longitude Coordinates

I successfully added a feature to display the LAT LON readout of the cursor location on my website by following the tutorial provided in This Mapbox GL JS Tutorial However, the output I receive is in this format: {"lng:-74.949147382928,"lat":40.438292204 ...

Issue with Electron: parent window not being recognized in dialog.showMessageBox() causing modal functionality to fail

Struggling with the basics of Electron, I can't seem to make a dialog box modal no matter what technique I try. Every attempt I make ends in failure - either the dialog box isn't modal, or it's totally empty (...and still not modal). const ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked. For the pre ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...