Reputation: 14297
I tried this:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace("(", "").replace(")", "");
It works for all double and single quotes but for parentheses, this only replaces the first parenthesis in the string.
How can I make it work to replace all parentheses in the string using JavaScript? Or replace all special characters in a string?
Upvotes: 32
Views: 67431
Reputation: 82
This can solve the problem:
myString = myString.replace(/\"|\'|\(|\)/)
Example
Upvotes: 0
Reputation: 6532
The string-based replace method will not replace globally. As such, you probably want to use the regex-based replacing method. It should be noted:
You need to escape (
and )
as they are used for group matching:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
Upvotes: 0
Reputation: 13476
Try the following:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
A little bit of REGEX to grab those pesky parentheses.
Upvotes: 54
Reputation: 4481
Just one replace will do:
"\"a(b)c'd{e}f[g]".replace(/[\(\)\[\]{}'"]/g,"")
Upvotes: 2
Reputation: 236092
You can also use a regular experession if you're looking for parenthesis, you just need to escape them.
mystring = mystring.replace(/\(|\)/g, '');
This will remove all (
and )
in the entire string.
Upvotes: 3
Reputation: 25465
That's because to replace multiple occurrences you must use a regex as the search string where you are using a string literal. As you have found searching by strings will only replace the first occurrence.
Upvotes: 0
Reputation: 78540
You should use something more like this:
mystring = mystring.replace(/["'()]/g,"");
The reason it wasn't working for the others is because you forgot the "global" argument (g)
note that [...]
is a character class. anything between those brackets is replaced.
Upvotes: 30
Reputation: 16061
That should work :
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
Upvotes: 0
Reputation: 6136
You should be able to do this in a single replace statement.
mystring = mystring.replace(/["'\(\)]/g, "");
If you're trying to replace all special characters you might want to use a pattern like this.
mystring = mystring.replace(/\W/g, "");
Which will replace any non-word character.
Upvotes: 7