Tips for eliminating duplicate words and potentially incorporating new terms into a text

Is there a way to eliminate specific words that are repeated exactly twice in a string, and if possible, add the word "and"? This should only apply to certain characters.

For instance, take the following example: "Intruction in seated LE AROM x10 each instruction in standing LE AROM x10 each."

The desired outcome is: "Instruction in seated LE AROM and standing LE AROM x10 each".

I attempted various methods such as looping through the string and removing duplicates, but it caused me to lose needed information. I also experimented with a solution from another individual's query, although they were focused on counting occurrences of a word rather than my particular issue.

function removeDuplicate(str) {
   let words = JSON.stringify(str).toLowerCase().split(' ')
    
    let wordsCount = {}

    words.forEach(word => {
        wordsCount[word] = (wordsCount[word] || 0) + 1
    })
    
}

Answer №1

Your provided example contradicts the explanations you have given.

You mentioned that "Instruction" is only removed once, while 'x10' and 'each' are removed twice. What exactly should 'and' replace in this scenario?

If your goal is to replace "x10 each" with "and", there is a JavaScript method available for that:

const initial = 'Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each';
const wished = initial.replaceAll('x10 each', 'and');
// Instruction in seated LE AROM and instruction in standing LE AROM and

If you wish to replace words that appear twice with 'end', you can utilize the filter and includes methods:

const initial = 'Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each';
const toRemove = ['x10', 'each'];

function removeDuplicate(str, arr, repl) {
    const words = str.toLowerCase().split(' ');
    let wished = str;

    words.forEach(word => {
        if (words.filter(elem => elem === word).length === 2 && arr.includes(word)) {
            wished = wished.replaceAll(word, repl);
        }
    });

    return wished;
}
// Instruction in seated LE AROM and and instruction in standing LE AROM and and

It appears that you may be looking for a different solution.

Answer №2

One way to track how often a specific word appears in a string is by using a counter, allowing you to then access the word based on its key or value. From there, you can decide which words to keep or remove using an if(){}else{} statement or even a switch statement.

It can be challenging to identify which words you want to keep if they appear multiple times in the array of words.

To address this, you can create a count of each word's occurrences and then selectively remove certain words from the array "arrToChange" based on your criteria, before converting the updated array back into a string.

            let originalString = "Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each";

            /* Within arrToChange, you have the option to eliminate words by their corresponding indexes in arr (uppercase), allowing you to maintain the original wording as it appears in the initial string.*/

            const arrToChange = originalString.split(" ");
            const arr = originalString.toUpperCase().split(" ");
            const counts = {};

            for (const num of arr) {
                if(counts[num]){
                    counts[num] ++;
                }else{
                    counts[num] = 1;
                }
            }
            
            console.log("arrToChange = " + arrToChange);
            console.log("arr = " + arr);
            console.log("Object counts = ");
            console.log(counts);
            
            console.log("Object.keys   = " + Object.keys(counts));
            console.log("Object.values = " + Object.values(counts));
            
            // If you prefer an Array of Arrays
            // This will provide you with an array structured like so:
            // [["Intruction",1],["in",2],["seated",1],...]
            console.log("");
            console.log("console.log(Object.entries(counts)); =>");
            console.log(Object.entries(counts));
            

By counting the occurrences and identifying the words to remove within the array arrToChange, you simply need to locate the indexes of these words for deletion...

Answer №3

Understanding your intentions can be a bit challenging. Here is my best attempt based on the information provided:

const orig = "Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each"
const re = /\b(.+)(\s.*?\s)(.+)\s.*?\1(.*?)\3/
const result = orig.replace(re, '$1$2and$4$3')
console.log(result)
// => Instruction in seated and standing LE AROM x10 each

The regular expression will capture the following patterns:

( in)( seated )(LE AROM x10 each) instruction{ in}( standing ){LE AROM x10 each}

By using .replace, the sentence is rearranged with the captures and the word "and" added:

( in)( seated )and( standing )(LE AROM x10 each)

If you need to repeat "LE AROM," you can explicitly include it in the pattern like this:

const orig = "Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each"
const re = /\b(.+)(\s.*? LE AROM\s)(.+)\s.*?\1(.*?)\3/
const result = orig.replace(re, '$1$2and$4$3')
console.log(result)
// => Instruction in seated LE AROM and standing LE AROM x10 each

Alternatively, if "LE AROM" is all uppercase and needs to be repeated, you can restrict uppercase letters in the third group:

const orig = "Instruction in seated LE AROM x10 each instruction in standing LE AROM x10 each"
const re = /\b(.+)(\s.*?\s)([^A-Z]+)\s.*?\1(.*?)\3/
const result = orig.replace(re, '$1$2and$4$3')
console.log(result)
// => Instruction in seated LE AROM and standing LE AROM x10 each

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

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap. My goal is to save a .aspx page as an HTML file within my application. Upon writing the code: using System; using System.Collections.Generic; using System.Linq; using S ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...

JavaScript special character encoding techniques

I'm trying to create a function to remove special characters in my JavaScript code. However, whenever I try using chr(46), it throws a syntax error. Does anyone have any suggestions on how I can successfully implement chr(46) in my JS code? storageV ...

Navigate to a precise point in a video using react hooks in videojs

I am currently working on adding a feature that allows users to skip forward or backward by 15 seconds in a video. However, I am encountering difficulties when it comes to updating and setting the current time accordingly. const videoNode = useRef(null); ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

Transforming an individual array into a multi-dimensional array

Just to be upfront, I had to figure this out for a project. I needed to convert a single array into a multidimensional array within a method. To solve the problem, I came up with the following code by first returning it to another one-dimensional array and ...

jQuery's element loading function fails to work with ajax requests

When trying to preload ajax data before attaching it to a div, I utilized the following code: $.ajax({ url: 'ajax.php', data: { modelID:id }, type: 'post', success: function(result){ $(result).load(function(){ ...

Is there a way to select multiple elements with the same class using getElementByClassName instead of only obtaining the first element with that class designation?

I recently started learning JavaScript, and I'm still struggling to grasp many concepts. I'm currently working on styling buttons on my website to match the existing ones, but I'm unable to edit the plugin's HTML directly. I was able to ...

Changing Coordinated Universal Time to Pacific Standard Time with Moment Timezone in JavaScript

I am attempting to set the variable "formattedLocalTime" to Pacific time using the following snippet of code. Despite the fact that the chrome debugger shows "locTime" as "Tue Sep 30 2014 16:17:25," which is the expected value, the formattedLocalTime on t ...

Having difficulty pinpointing and deleting an added element using jQuery or JavaScript

My current task involves: Fetching input from a form field and adding the data to a div called option-badges Each badge in the div has a X button for removing the item if necessary The issue at hand: I am facing difficulty in removing the newly appended ...

Troubleshooting: ng-disabled not function properly in Angular.js

My goal is to only allow the button to be enabled if there is text in the textfield, but for some reason I am unable to make ng-disabled work: <form novalidate> <button type="submit" ng-click="add('+')" ng-disabled="bittext.$invalid ...

Looking to duplicate the elements with the click of a button?

I am in need of assistance with my registration form. My goal is to move the elements contained within the <fieldset> tags to the end of a row when the user clicks the + button. The result you see initially has been recreated. Thank you for your s ...

What is the proper way to utilize the value of a Node.js promise in a different function?

In my Node.js application, I have two functions defined. The first function is structured like this: function checkAdd ( address /* : string | void */ ) /* :Promise<Object[]> */ { var convertToLowerCase = address.toLowerCase() return Promi ...

error message remains visible even after correct input is entered

I am new to React and attempting to create a multi-step form using Reactjs and Material-ui. The form validation and submit buttons are working perfectly fine. However, I have encountered an issue with the code where if a field is empty and I try to proceed ...

Extracting values from an event in Vue.js: A step-by-step guide

When working with Vue.js, I use the following code to fire an event: this.$emit("change", this.data); The parent component then receives this data, which is in the form of an object containing values and an observer. It looks like this: { data ...

What could be causing this error in the jQuery AJAX post request, even though the post was actually successful?

I created a blogging platform using Laravel 8. Currently, I am focused on implementing comment submissions and replies using jQuery (v3.5.0) AJAX. This is the function for adding a comment: public function add_comment( Request $request ) { $rules = [ ...

Why isn't my lightbox able to read this specific property?

A gallery was created using both lightgallery and cycle2. Cycle is a carousel plugin while lightgallery is a lightbox gallery. Clicking on an image in the carousel opens it in the lightbox. Everything worked perfectly until a category in the carousel was ...