1

I am attempting to use the replace() function on a large amount of text, to filter out "[","{","(", and many other special characters. I initially attempted to just say:

replace(/"{"/g," ")

But this did not work, I tried a series of variations like this, using:

"/{/"g 

or

"/{/g"

Yet, none of them worked. I have also tried attaching the first replace parameter to a variable as they do in the Mozilla tutorial.

var replacingStuff = /{/g;
str.replace(replacingStuff," ");

Does anyone have any ideas on how to fix this problem?

Darrow Hartman
  • 4,142
  • 2
  • 17
  • 36
  • You need to escape characters with a special meaning in regex with backslashes. – Pinke Helga Mar 02 '19 at 19:58
  • I am using the backslash to make the replace function global, therefore I cannot remove them. – Darrow Hartman Mar 02 '19 at 19:59
  • Don't say you can't before you didn't try. That's JavaScript basics. `.replace(/\[/g, '')` or multiple chars within brackets. – Pinke Helga Mar 02 '19 at 20:02
  • Possible duplicate of [Is there a RegExp.escape function in Javascript?](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) – Pinke Helga Mar 02 '19 at 20:14

1 Answers1

1

Use /[/[]/g as the regex to get rid of [

Basically, if you want to get rid of a certain character, it needs to be in brackets. For example, if you wanted to replace the characters a, b, and c, you would use the regex /[abc]/g.

You can use the snippet below. The regex pattern I used was /[[{(]/g. It may seem a bit overwhelming, but all it's doing is removing all the characters inside the bracket. Strip away the outside brackets and you get [{( which is the characters the regex will replace.

var text = "[fas[ds{ed[d{s(fasd[fa(sd"

console.log(text.replace(/[[{(]/g, ''));
Aniket G
  • 3,471
  • 1
  • 13
  • 39