What is a clever approach in Javascript to replace consecutive duplicate phrases in a randomized string?

In a given string, I am looking to replace repeated phrases that are next to the original phrase. These phrases are not known in advance.

I attempted using regex to substitute the duplicate phrase with " | ". See below for my approach.

Original String:

"FounderFounder Breakthrough Energy Breakthrough Energy 2015 - Present · 8 yrs2015 - Present · 8 yrs"

Expected Result:

"Founder | Breakthrough Energy | 2015 - Present · 8 yrs |"

// Regex function
function replaceDuplicateSubstrings(string) {
    var regex = /(\b\w+\b)\s+\1/g;
    return string.replace(regex, "$1 |");
}
// Sample String
var exampleString = "FounderFounder Breakthrough Energy Breakthrough Energy 2015 - Present · 8 yrs2015 - Present · 8 yrs";

// Console Write
console.log(replaceDuplicateSubstrings(exampleString)); 


// The expected result should be: "Founder | Breakthrough Energy | 2015 - Present · 8 yrs |"
// However, it currently outputs the same input string without any changes.
`


Answer №1

Feel free to utilize the following code snippet:

const str = "FounderFounder Breakthrough Energy Breakthrough Energy 2015 - Present · 8 yrs2015 - Present · 8 yrs";
var replacedString = str.replace(/(.+?)\1/g, "$1 |");

console.log(replacedString)

RegEx Playground

The regular expression pattern (.+?) captures and matches one or more of any characters in group #1. It is followed by a back-reference \1 to ensure adjacent repeated text is caught.

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

fill out an HTML form and send it in

When submitting a form with two components, only the first form 'School' and the submit button itself are successfully submitted. The second form 'pool' seems to disappear somehow. <form method='get'> <select nam ...

JavaScript-based tool for extracting content from Sketch file

My goal is to extract the contents of a .sketch file. I have a file named myfile.sketch. When I rename the file extension to myfile.zip and extract it in Finder, I can see the files inside. However, when I try the same process on the server using Node.js ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

Creating unit tests for a javascript method that employs a JWT token

Currently, I'm facing a challenge when writing unit tests in JavaScript for a method that includes JWT token validation. The method should only fetch results if the token is valid. I'm looking to mock the JWT token and return results. I've ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

Creating multiple carousels using a loop: Passing `$(this)` to Slick.js plugin

Is there a way to correctly pass $(this).find('.option') and $(this).find('.prev_next') to Slick.js? Currently, I am encountering the error message: Syntax error, unrecognized expression: [object Object]:not(.slick-cloned) in jquery-2.1 ...

Transferring JSON data using AJAX

I am having trouble sending JSON via AJAX using pure JavaScript. While I can successfully retrieve values back from PHP, I am struggling to retrieve a specific JSON array. var mname = ["john", "mary", "eva"]; var fname = 678; clicked_keyword_test = {"last ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

Creating a regular expression variable in Mongoose: A step-by-step guide

I am looking for a solution to incorporate a variable pattern in mongoose: router.get('/search/:name', async(req, res) => { name = req.params.name; const products = await Product.find({ name: /.*name*/i }).limit(10); res.send(prod ...

Tips for making a 2D grid on a webpage

Is there a way to implement a 10x10 grid on a webpage where users can click anywhere on the grid and have their (x, y) position recorded with one decimal place accuracy, covering values between 0.0-10.0 or 0.1-9.9? Appreciate any guidance! ...

Choose the radio button by clicking using jQuery

I am attempting to use jQuery to select a radio button on click. Despite multiple attempts, I have been unsuccessful so far. Here is my current code: JS $(document).ready(function() { $("#payment").click(function(event) { event.preventDefault() ...

Why is it that I always have to click the slideToggle button twice after refreshing my page in order to hide the untoggled form?

In the project I am working on, there is a button that is supposed to toggle down a form when clicked. Everything works as expected except for one scenario. Expected behavior: When the form is not visible, clicking the toggle button should make the form a ...

Tips for preventing the initiation of a session on a specific Express route?

Currently, I rely on ExpressJS as my app framework and also utilize connect-memcached for managing sessions within Express. app.use( express.session({ secret: "blah blah", store: new MemcachedStore({ ... }) })); This setup has been very effective. Ho ...

Sequelize error: Foreign key mentioned, yet not found in the table

I recently started using Sequelize and have been relying heavily on the documentation available here. The documentation mentions the importance of using hasOne(), hasMany(), and belongsTo() to automatically add foreign key constraints. In my case, I am wor ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

Octokit's webhooks are unresponsive when accessed via the Express server

After setting up a webhook handler using Octokit, I encountered an issue where the webhook server was not functioning properly when integrated with the Express server. Despite the documentation stating that it supports web servers, I was only receiving a r ...

Using JavaScript to extract data from AJAX response within an HTML document

My code involves utilizing AJAX calls with JavaScript. function loadFacility(callback) { //alert('In loadFacility'); var xmlhttp; var keys=document.firstCallInformation.facilityselect.value; var urls="http://localhost:8080/webfdm ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...