简体   繁体   中英

Replace regExp with certain characters (Javascript)

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!

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 />");

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.

您需要转义方括号。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM