![](/img/trans.png)
[英]JavaScript Regexp to replace a value only when it follows certain characters?
[英]Replace regExp with certain characters (Javascript)
我在尝试替换字符串中的某些特殊字符组时遇到一些问题。 特别
str = 'This is some demo copy[300]this should remove the brackets and the copy 300.'
我一直在尝试用
str.replace(/[300]/g, "<br />");
没有这种运气。 我似乎对必须删除的方括号[]
感到困惑。 我知道我可以单独删除它们,然后替换300,但是我需要一起替换。
它应该返回:
This is some demo copy
this should remove the brackets and the copy 300.
任何建议都是非常感激的,因为我是正则表达式的新手。
提前致谢!
在正则表达式中, [
和]
具有特殊含义。 您要求替换可能找到的任何3
或0
。
像这样逃避括号:
str.replace(/\[300\]/g, "<br />");
这是给您的正则表达式:
/\[300\]/g
正则表达式语言中的方括号定义字符集。 在您的情况下,您只需要使它们脱离运行即可。
您需要转义方括号。
str.replace(/\[300\]/g, "<br />");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.