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.
`