Darrow Hartman
Darrow Hartman

Reputation: 4383

replace function for special characters

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?

Upvotes: 1

Views: 121

Answers (1)

Aniket G
Aniket G

Reputation: 3512

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, ''));

Upvotes: 1

Related Questions