1

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!

3 Answers 3

4

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 />");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

That would also replace the bare "300" at the end (since you made the brackets optional), which isn't what the OP is after.
Hm.. I was sure he wants to replace both, whenever there are brackets or there are not. Most probably I misread. Anyway, if so, just removed ?.
0

You need to escape your square brackets.

str.replace(/\[300\]/g, "<br />");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.