sarcastasaur sarcastasaur - 22 days ago 7
Javascript Question

Remove specific words except last in JavaScript?

I have a sentence that I would like to have only the last 'and' remaining, and remove the others.

"Lions, and tigers, and bears, and elephants", and I would like to turn this into:

"Lions, tigers, bears, and elephants".

I have tried using a regex pattern like

str = str.replace(/and([^and]*)$/, '$1');
which obviously didn't work. Thanks.

Answer

Use this regex:

and (?=.*and)
  • and matches any and followed by a space. Space is matched so it is removed on replacement, to prevent having 2 spaces
  • (?=.*and) is a lookahead, meaning it will only match if followed by .*and, if followed by and

Use this code:

str = str.replace(/and (?=.*and)/g, '');