简体   繁体   中英

Find and replace word - case insensitive

I am trying to find and replace the "[num]" with my own word, but this does not work. If I remove "[" and "]" it works.

response = response.replace(/[num]/i, 'my text'); 

您需要转义它们,因为正则表达式中使用[]指定字符集

response = response.replace(/\[num\]/i, 'my text'); 

Try this:

response = response.replace(/\[num\]/i, 'my text'); 

JSFIDDLE DEMO

On a side note:

If you want to replace text inside a square bracket then you can use this regex:

/\[[^\]]+\]/g

The square brackets denote [] character classes.

From regular-expressions.info

With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae]. You could use this in gr[ae]y to match either gray or grey.

So the regex.replace in your code will replace, any occurence of "n or u or m" with "my text".

如果有效,为什么不删除“ [”和“]”,您能否提供,以便我可以弄清楚您实际上在做什么?

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