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
  • 65,341
  • 71
  • 269
  • 466

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
  • 14,906
  • 5
  • 47
  • 53
0

Escape the characters with special treatment with backslash.

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

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

Barmar
  • 741,623
  • 53
  • 500
  • 612