0

I have a simple task but I'm not sure of the syntax.

I have a string and want to replace any occurrences of '[', ']', or '.' with an underscore ('_').

I know that string.replace() supports regular expressions, which also give special treatment to [ and ].

Jonathan Wood
  • 61,921
  • 66
  • 246
  • 419

2 Answers2

1

Use replaceAll for that

** Note, replace will also work since this a global search.

const src = '/[[\].]/g';
const target = '_';

const formated = string.replaceAll(src, target);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

Ran Turner
  • 8,973
  • 3
  • 23
  • 37
0

Escape the characters with special treatment with backslash.

string = string.replace(/[[\].]/g, '_');

Note that [ and . don't receive special treatment inside [].

Barmar
  • 669,327
  • 51
  • 454
  • 560