ohmu
ohmu

Reputation: 19760

Javascript regex matching comma when it's not supposed to

I cannot figure out this javascript little oddity that's occurs in Firefox 7.0.1 and Google Chrome 14.0.835.202 (I haven't tested any other versions). Why does /[+-.]/g match commas (,) in addition to plus signs (+), dashes (-) and periods (.)?

// Firebug
>>> "Hello, World++--..".match(/[+-.]/g);
[",", "+", "+", "-", "-", ".", "."]
>>> "Hello, World".match(/[+-.]/g);
[","]

// Chrome Developer Tools:
> "Hello, World++--..".match(/[+-.]/g);
  [",", "+", "+", "-", "-", ".", "."]
> "Hello, World".match(/[+-.]/g);
  [","]

Okay, so maybe I need to escape the period (.)

// Firebug
>>> "Hello, World!".match(/[+-\.]/g);
[","]

// Chrome Developer Tools
> "Hello, World!".match(/[+-\.]/g);
  [","]

Nope. But if I change the order of the plus (+) and dash (-) it stops matching the comma (,).

// Firebug
>>> "Hello, World".match(/[-+.]/g);
null

// Chrome Developer Tools
> "Hello, World".match(/[-+.]/g);
  null

This makes no sense to me. It seems odd that both Firefox and Chrome would share the same regex bug. Does anybody know why this is?

Upvotes: 1

Views: 240

Answers (2)

gilly3
gilly3

Reputation: 91497

Using - within square brackets between two other characters matches all characters in the range between those characters, inclusive. So, + is U+002B and . is U+002E. All of the characters in that range would include:

+ U+002B
, U+002C
- U+002D
. U+002E

That it was matching the 3 characters you included plus one more is just a confusing coincidence. Your answer is in your question... Move the - to be the first character in the square brackets:

/[-+.]/g

Alternatively, you can escape the -:

/[+\-.]/g

Upvotes: 2

Jens Erat
Jens Erat

Reputation: 38682

Use [+\-.].

- masks a range and must be escaped.

Upvotes: 10

Related Questions