1

Let's say I have a string,

"Testing   éééé     123" 

I want to strip out all the occurrences of

é 

and all the spaces that come before and after, and just replace it with one space so it ends up like:

"Testing 123" 

How do you capture recurrence of a sequence of characters i.e. the repeating

é

, for a Javascript regular expression?

1
  • When you say repeating characters, "t" is also repeating in the string you gave. I guess you want to remove all non-alphabet and non-numeric characters. Dec 25, 2018 at 1:19

2 Answers 2

2

Backreferences are your friend for this kind of thing.

A backreference is allowed in regular expressions, allowing you to match the same repeated pattern as a first one. For instance, let's match your char entities:

/(&#x[0-9a-f]+;)\1+/i

This will match the first char entity it finds, then proceeds to chain any number of identical entities after it.

If you want to remove repeated characters, you can even extend it further to this:

/(.+)\1+/i

Which will match any sequence of repeated characters (including spaces) and compounded patterns. Do note, however, that this will get rid of repeated letters in text if there are any.

1

Put the sequence in a group and repeat that group with + - then, you can replace that (and surrounding spaces) with a single space:

const input = "Testing   éééé     123";
const output = input.replace(/ *(?:é)+ */, ' ');
console.log(output);

If there may be additional repeated sequences, eg

"Testing   éééé     123 foobar éé baz";

Then use the global flag as well:

.replace(/ *(?:é)+ */g, ' ');
//                        ^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.