Kreitzo Kreitzo - 10 days ago 4x
Javascript Question

JS Regex: Remove anything (ONLY) after a word

I want to remove all of the symbols (The symbol depends on what I select at the time) after each word, without knowing what the word could be. But leave them in before each word.

A couple of examples:

!!hello! my! !!name!!! is !!bob!!
should return...

!!hello my !!name is !!bob
; for


$remove$ the$ targetted$@ $$symbol$$@ only $after$ a $word$
should return...

$remove the targetted@ $$symbol@ only $after a $word
; for


You need to use capture groups and replace:

"!!hello! my! !!name!!! is !!bob!!".replace(/([a-zA-Z]+)(!+)/g, '$1');

Which works for your test string. To work for any generic character or group of characters:

var stripTrailing = trail => {
  let regex = new RegExp(`([a-zA-Z0-9]+)(${trail}+)`, 'g');
  return str => str.replace(regex, '$1');

Note that this fails on any characters that have meaning in a regular expression: []{}+*^$. etc. Escaping those programmatically is left as an exercise for the reader.