To match repetitive strings (without knowing the exact string), you need to use capturing groups and backreferences.
Depending on the definition of 'string', there are multiple solutions, e.g.:
Any character sequence: ^(.+?)\1+
- Matches e. g. "AAA" of "AAA B", "AA" of "AA AA B", whitespace
Character sequence ending on whitespace: ^(.+?\s)\1+
- Matches e. g. "AA AA " of "AA AA B", whitespace
Character sequence ending on word boundary: ^(.+?\b)\1+
- Doesn't match whitespace. This is probably what you want.
If you want to match the remaining, non-repetitive part of the string, simply add a second capturing group (.*)
to the above regex:
// Get the repeated word:
console.log('Copy of Copy of Copy of This is my String'.match(/^(.+?\b)\1+(.*)/)[1]);
// Get the remaining string:
console.log('Copy of Copy of Copy of This is my String'.match(/^(.+?\b)\1+(.*)/)[2]);
Explanation: ^
matches the start of our string, the capturing group (.+?\b)
matches any character one or more times followed by a word boundary and allows us to reference to its match later via \1
. Since we are looking for one or more repetitions, we try to match against \1+
.
I recommend https://regex101.com/#javascript or similar tools to better understand and explore regex.