Skip to content
Advertisement

How can I find repeating pairs of characters with a regex?

Trying to use regex to replace any occurrences of any set of two characters which repeat in a string. I would like for such patterns to be replaced with one occurrence of the repeating substring and the number of times it was repeated.

For example, in this string below, I would like:

qwertyabababababababababababa

to become:

qwertyab11a

Similarly,

a a a a a a a a a a

should become:

a 9a

I have tried running code similar to this:

console.log("hello, this test did not work".replace(/([DD]+)/g, (...r) => {
  console.log(r);
  return r[1].slice(0, 2) + r[1].length / 2;
}));

but the above obviously didn’t work, and returned this:

he14.5

Advertisement

Answer

You can use a so-called back-reference (1) to match a repetition of a captured group:

console.log("did nana mouskouri sing mama mia".replace(/(DD)1+/g, (all, grp) => {
    return grp + all.length / 2;
}));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement