DEV Community

#25 - Remove consecutive duplicate words CodeWars Kata (7 kyu)

Cesar Del rio on January 25, 2022

Instructions Your task is to remove all consecutive duplicate words from a string, leaving only first words entries. For example: In...
Collapse
 
lexlohr profile image
Alex Lohr

This one you can solve with a single RegExp:

const removeConsecutiveDuplicates =
  (input) => input.replace(/(\w+) \1/g, "$1")
// \1 matches the last match made with (\w+)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fjones profile image
FJones

Yeah, but backreferences are evil. ;)

Collapse
 
lexlohr profile image
Alex Lohr

Still pretty effective, especially in this case. ;)

Collapse
 
cesar__dlr profile image
Cesar Del rio

I don't know too much about regex, I think I need to do some research about it 😅
what does the "$1" do?

Collapse
 
lexlohr profile image
Alex Lohr

It inserts the first match inside brackets.

Thread Thread
 
cesar__dlr profile image
Cesar Del rio

Oh right, so it just leaves the first match and the other one gets replaced, am I rigth?

Thread Thread
 
lexlohr profile image
Alex Lohr

Exactly.

Thread Thread
 
cesar__dlr profile image
Cesar Del rio

cool 🔥

Collapse
 
matetlot profile image
Matetlot

What a conversation of genius, well donne guys !

Collapse
 
cesar__dlr profile image
Cesar Del rio

Thanks bro 🙌

Collapse
 
cesar__dlr profile image
Cesar Del rio

Great Solution, I didn't know that you could call the filtered array as a parameter! 🙌