Utilizing Regex to eliminate consecutive duplicates in a string separated by spaces

My current challenge involves removing only sequential duplicates from a string. For example, in the string "1 2 3 3 2 1", I want to remove one of the consecutive 3's so it becomes "1 2 3 2 1". I thought I had the solution figured out, but when I tested it, I encountered a scenario where it failed. Despite trying various combinations, nothing seems to work. It must be something simple that I am missing.

Below is some Javascript code demonstrating the issue. The first testVal string is handled correctly, but the commented-out testVal string does not produce the correct result.

// The following string should reduce to: MTC MTCA MTC ORD MTC (it does).
var testVal = "MTC MTC MTCA MTC MTC MTC ORD MTC";

// The following string should reduce to: MTC (it does not. Result = MTC MTC).
// The string MTC MTC MTC MTC also only reduces to MTC MTC, so I'm thinking
// it's a whitespace issue.
// var testVal = "MTC MTC";

while (/\b(\s*\w+\s*)\b\1/.test(testVal)) {
    testVal = testVal.replace(/\b(\s*\w+\s*)\b\1/g,'$1');
}

alert(testVal1);

Answer №1

Make sure to count the whitespace as a separate entity when looking for duplicate words.

/\b(\w+)\s+\1\b/

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

Executing functions and setting element values upon loading in Javascript

I am currently working on updating a small Javascript function that assigns an active class to the parent <div> of a group of radio buttons when the page loads and also when there's a change event. The existing function looks like this: functi ...

How to Utilize Muuri Javascript Library with Bootstrap Tabs: Resizing Required for Expansion?

Struggling for days and feeling frustrated, I'm hoping someone can help me crack this mystery. My idea is straightforward - three Bootstrap 4 tabs with drag and drop functionality inside each, all displayed in a responsive stacked masonry layout. To a ...

Encountering an issue with ReactJS + Redux where the error message states: "Error in prop type: The Right-hand side of 'instanceof' cannot be called"

Currently working on a web app project in React with Redux for global state management. A puzzling issue has arisen - we're receiving warnings in the browser console. How can we resolve this? It seems related to prop types declaration, but the soluti ...

How to customize the center text of Chart.js doughnut chart

I've tried every search I can think of, but still can't find a solution to my problem. I want to customize the text in the middle of my doughnut chart (not tooltips). The chart is created using Chart.js and includes a percentage in the center. E ...

When using the executeScript() method, it unexpectedly gives a null result instead of allowing me to scroll

The following code snippet is used to scroll horizontally within a web page: WebElement element=driver.findElement(By.xpath("//div[@class='table-wrapper']")); JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("arguments[0].scroll ...

The `<Outlet/>` from react-router is being rendered in a location outside of its intended wrapper div

Utilizing MUI for crafting a straightforward dashboard featuring an <AppBar>, a side <Drawer>, my component appears as follows: <> <AppBar> // code omitted <AppBar/> <Drawer> // code omitted <Drawer/> / ...

Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage: <select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br> I'm curious if there ...

Using three.js to showcase a sequence of various objects consecutively

I am currently working with three.js to create mesh and textures for 20 different objects. Below, you will find an example object. My goal is to display each of these 20 objects sequentially on the screen. I want to show the first object, have it stay on ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Removing data from firestore/storage does not follow the expected pathway

I have created an image gallery for users using Firebase Storage and React, allowing them to upload and delete images. However, I am facing an issue where the deletion process is taking longer than expected. Expected flow: User clicks on the trashcan ico ...

Include characteristics in JSX.Element following its declaration

Suppose I have an item in a dictionary with the following structure: let item = { element: <myElement/>, color: "#0e76a8" } Is it possible to add a style attribute to the item.element within the render() method? I tried the following appro ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

interactive switch using font awesome icons and jquery

Initially, I assumed this would be an easy task, but I've encountered some difficulties in making it function smoothly. Although I am able to toggle once using .show and .hide, I am unable to toggle back. Any assistance would be greatly appreciated. ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Revamping a pie chart by incorporating a fresh dataset containing additional data points

I recently started learning D3 and have been exploring various pie chart tutorials. Specifically, I've been following the tutorials by Mike Bostock. http://bl.ocks.org/mbostock/1346410 However, I'm struggling with updating a donut chart from on ...

Tips for integrating the Bootstrap 5 JS file (bootstrap.bundle.js) into Laravel 8

I have successfully integrated Bootstrap v5.1.0 into my Laravel 8 project using npm. Now, I am facing an issue with including bootstrap.bundle.js in my public/app.js. After installing popperjs, I added the following code to my resources/js/bootstrap.js: t ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

Attempting to implement image switching with hover effects and clickable regions

Hey there, I'm currently working on a fun little project and could use some guidance on how to achieve a specific effect. The website in question is [redacted], and you can view the code I've used so far at [redacted]. You'll find a code blo ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

What is the best way to ensure all requests have been completed before proceeding?

Is there a way to ensure that the sortOrder function only runs once the getOrders function has fully completed its execution? I have considered using a callback, but I am unsure of how to implement it. Do you have any suggestions on how I can achieve this ...