2

There are many posts like this and I have found a few solutions but there are not perfect. One of them:

"aabbhahahahahahahahahahahasetsetset".replace(/[^\w\s]|(.+)\1+/gi, '$1')

The results is:

abhahahahahahaset

I want to get result:

abhaset

How to do this ?

3
  • Our answers fix your specific problem. But I wonder, what is your desired output for abcabcDabcabcD. Do you want abcDabcD or abcabcD? So longest, or shortest repetition if there are nested repetitions. Commented Apr 25, 2013 at 13:09
  • Hmm, good question. I want your string to be abcD Commented Apr 25, 2013 at 13:14
  • Ah okay, then just run the replacement until it doesn't change any more. Commented Apr 25, 2013 at 13:16

2 Answers 2

4

.+ is greedy. It takes as much as it can. That is half of the has so that \1 can match the second half. Making the repetition ungreedy should do the trick:

/[^\w\s]|(.+?)\1+/gi

By the way, the i doesn't change anything here.

To get rid of nested repetitions (e.g. transform aaBBaaBB into aB (via aaBB or aBaB)) simply run the replacement multiple times until the result does not change any more.

var pattern = /[^\w\s]|(.+?)\1+/g;

var output = "aaBBaaBB";
var input;

do
{
    input = output;
    output = input.replace(pattern, "$1");
} while (input != output)

I admit the naming of output is a bit awkward for the first repetition, but you know... the two most difficult problems in computer science are cache invalidation, naming things and off-by-one errors.

Sign up to request clarification or add additional context in comments.

Comments

2

.+ will match the maximum amount possible, so hahahaha satisfies (.+)\1 with haha and haha. You want to match the minimum amount possible, so use a reluctant quantifier.

"aabbhahahahahahahahahahahasetsetset".replace(/[^\w\s]|(.+?)\1+/gi, '$1')

http://jsfiddle.net/HQRDg/

1 Comment

Thank you very much, but m.buettner was first :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.