3

Very new to RegEx

I need to remove whitespace after / character in a string if it exists

Ex

find/ replace other stuff >> find/replace other stuff

I am trying .replace(/[/]+$/g, "") but it has no effect

I am using this in a Google Apps Script

Rubén
  • 34,714
  • 9
  • 70
  • 166
Einarr
  • 214
  • 2
  • 14
  • Possible duplicate of [regex remove white space after text](https://stackoverflow.com/questions/14573706/regex-remove-white-space-after-text) – Rubén Jul 09 '18 at 17:45

1 Answers1

2

You may match a forward slash (\/, escaped since / is used as a regex delimiter char) and then any 1 or more whitespaces (\s+) to replace with a backslash:

s = s.replace(/\/\s+/g, '')

Or, capture the forward slash with a capturing group (a pair of unescaped parentheses, (...)), and replace with a replacement backreference $1:

s = s.replace(/(\/)\s+/g, '$1')

See the JS demo:

console.log("/abc/   spaces/   more spaces".replace(/\/\s+/g, '/'))
console.log("/abc/   spaces/   more spaces".replace(/(\/)\s+/g, '$1'))

All occurrences are replaced because g (global) modifier is used.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563