-3

How do I remove all instances of two different letters in a string?

For example, I want to remove 'a' and 'c' from 'abcabc' so that it becomes 'bb'.

I know I can't do 'abcabc'.replace(/a/g, '').replace(/c/g, '') but is there another regEx I can use so that I don't have to chain the replace function?

Thanks!

ShCh
  • 42
  • 5

3 Answers3

6

Alternative syntax:

"abcabc".replace(/[ac]/g, '')

This creates a custom character group.

Without Haste
  • 507
  • 2
  • 6
  • +1 - This is actually [faster](https://stackoverflow.com/q/22132450/2170192), and "scales good" if there are more characters (than two) to be removed. `a|c|e|f|h` vs `[acefh]` – Alex Shesterov Sep 17 '18 at 23:00
0

You can separate matches with a pipe:

'abcabc'.replace(/a|c/g, '')
Parziphal
  • 6,222
  • 4
  • 34
  • 36
0

/a|c/g ought to do it.

'abcabc'.replace(/a|c/g, '')

Ronak
  • 23
  • 1
  • 5