How to Extract Consecutive Characters in a JavaScript String?

To match consecutively repeating characters in a string, you can simply use a regular expression that uses a backreference to the same character that's matched in a capturing group.

For example, to match letters that appear consecutively in a string, you can do the following:

const str = 'aabbcccdde';
const pattern = /([a-z])\1+/g;
const matches = str.match(pattern);

console.log(matches); // ['aa', 'bb', 'ccc', 'dd']

In the example above, the capturing group matches characters a-z only once. Then right after, using a backreference to the capturing group (i.e. \1 — which refers to the first capturing group), the same character is matched again, one or more times. As a result, it matches characters that appear in the string consecutively.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.