Reputation: 1
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
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 stringBut if instead you actually need movement
, then this will do it for you:
console.log(
'mmoooovvvemmmeeent'.replace(/(.)\1+/g, '$1')
) // movement
(.)\1+
- capture repeated charactersg
- all of them'$1'
- replace with capture group 1, which is the repeated characterUpvotes: 0
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+
console.log("mmoooovvvemmmeeent".replace(/\bm+/, ''));
Upvotes: 1