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:
"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 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.