Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Javascript, what's an efficient way to replace adjacent duplicate phrases in a random string?

I’d like to replace duplicate phrases that appear adjacent to the original phrase in a string.
None of the phrases or strings are known at runtime.

I’ve tried some regex that I think should work, to replace the duplicate phrase with " | ". See below.

Example Input String:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Desired Output String

"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)); 


// Should log "Founder | Breakthrough Energy | 2015 - Present · 8 yrs |" to the console
// Instead logs the same input string with no changes: "FounderFounder Breakthrough Energy Breakthrough Energy 2015 - Present · 8 yrs2015 - Present · 8 yrs"
`


>Solution :

You may use this snippet:

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

console.log(repl)

RegEx Demo

RegEx Pattern (.+?)\1 matches 1+ of any characters and captures it in group #1. It must be immediately followed by back-reference \1 to make sure adjacent repeating text.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading