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 ].
CodePudding user response:
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
CodePudding user response:
Escape the characters with special treatment with backslash.
string = string.replace(/[[\].]/g, '_');
Note that [ and . don't receive special treatment inside [].
