Reputation: 325
I have having some issues trying to replace a certain group of special characters in a string. Specifically
str = 'This is some demo copy[300]this should remove the brackets and the copy 300.'
I have been trying to replace it with
str.replace(/[300]/g, "<br />");
with no such luck. I seem to be getting hung on with the brackets[]
that also need to be removed. I know that I can remove them individually, and then replace the 300 but I need to replace the set together.
It should return:
This is some demo copy
this should remove the brackets and the copy 300.
Any advice would be extremely appreciative as I am relatively new to regular expressions.
Thanks in advance!
Upvotes: 1
Views: 53
Reputation: 32511
You need to escape your square brackets.
str.replace(/\[300\]/g, "<br />");
Upvotes: 0
Reputation: 36438
In regular expressions, [
and ]
have special meaning. You're asking to replace any 3
or 0
that might be found.
Escape the brackets like so:
str.replace(/\[300\]/g, "<br />");
Upvotes: 4
Reputation: 145398
Here is a regex for you:
/\[300\]/g
Brackets in regular expressions language define a character set. In your case you simply need to escape them to make things working.
Upvotes: 0