CookieStack
CookieStack

Reputation: 1

Removal of repeated characters up to new character with regular expression

I’m trying to write a RegExp in JavaScript that removes all repeated characters from a string up to the point there is a new character.

at the moment I have:

'mmoooovvvemmmeeent'.replace(/.*m/,'')

This returns ent but I’d like it to return oooovvvemmmeeent

Any help is appreciated.

Upvotes: 0

Views: 42

Answers (2)

AndreasPizsa
AndreasPizsa

Reputation: 1746

This is going to give you oooovvvemmmeeent

console.log(
  'mmoooovvvemmmeeent'.replace(/(.)\1+/, '')
) // oooovvvemmmeeent

  • (.) - capture one character as a group
  • \1 - expect that same character again ("backreference to group 1")
  • + - one or more
  • '' - then replace that with an empty string

But if instead you actually need movement, then this will do it for you:

console.log(
  'mmoooovvvemmmeeent'.replace(/(.)\1+/g, '$1')
) // movement

  • (.)\1+ - capture repeated characters
  • g - all of them
  • '$1' - replace with capture group 1, which is the repeated character

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163217

You could use an anchor ^ or a word boundary \b, then repeat 1+ times the m char and replace with an empty string

\bm+

Regex demo

console.log("mmoooovvvemmmeeent".replace(/\bm+/, ''));

Upvotes: 1

Related Questions