user1427661
user1427661

Reputation: 11774

Non-traditional or Matching in Javascript Regex?

Correct me if I'm wrong, but I believe the regular expression ({|}) would traditionally match either a { or a }. But when I have a string like this: "{hello i'm a string}" and I call this function:

var album = $(song).data('album').replace(/({|})/, '', 'g');

Only the { is replaced, leaving the trailing }. What gives?

Upvotes: 2

Views: 37

Answers (1)

Cianan Sims
Cianan Sims

Reputation: 3429

I believe the non-standard flags parameter is ignored if the first argument is a regexp object. According to the MDN:

To perform a global search and replace, either include the g switch in the 
regular expression or if the first parameter is a string, include g in the 
flags parameter.

For your example, the following works:

> "{hello}".replace(/({|})/g, '')
> "hello"

Upvotes: 2

Related Questions