user3351236
user3351236

Reputation: 2538

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'); 

Upvotes: 0

Views: 92

Answers (4)

Dinesh Lamsal
Dinesh Lamsal

Reputation: 77

If it is working, why do not you do removing "[" and "]", can you provide so that i can figure out what you are really trying to so there?

Upvotes: 0

Kumaran
Kumaran

Reputation: 41

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".

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

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

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to escape them as [ and ] are used in regex to specify a character set

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

Upvotes: 2

Related Questions