0

I am trying to complete a coding challange on CodeWars and i am trying to use a regex expression instead of splitting it into an array etc.

My code is

const removeDuplicateWords = s => s.replace(/(\b\S.+\b)(?=.*\1)/g, "")

removeDuplicateWords('alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta');            

I have gotten to a point that it replaces all the duplicates but I cannot get rid of the white space at the beginning.

Native Browser JavaScript

=> ' alpha beta gamma delta'

can anyone help, please?

Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
JasonC
  • 71
  • 8

1 Answers1

4

You could simply use .trim() for this. String.prototype.trim()

This will remove all whitespace at the beginning and end of your string. Your end result would be:

const removeDuplicateWords = s => s.replace(/(\b\S.+\b)(?=.*\1)/g, "").trim();
Nick Abbott
  • 364
  • 1
  • 9
  • good solution @NickAbbott but it doesn't work for this case: `Company w/e 09/06/20 083020-090620` it returns: `Company w/e // 083020-090620` removing the date and keeping only `/` separator. It is because it captures the same digits. The following RegEx provides the expected result: `/(\b\S.+\b)(?=.*\b\1\b)/g` – David Leal Dec 06 '21 at 03:34