Duplicate Word in JS
Detects consecutive duplicate words using a backreference.
Try it in the JS tester →Pattern
regexJS
\b(\w+)\s+\1\b (flags: gi)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("\\b(\\w+)\\s+\\1\\b", "gi");
const input = "the the cat sat on the the mat";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
`\b(\w+)\b` captures a word. `\s+\1\b` matches whitespace followed by the same word (backreference `\1`). Case-insensitive.
Examples
Input
the the cat sat on the the matMatches
the thethe the
Input
no duplicates hereNo match
—