Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'B' matched by [a-z]?

a very simple & naive question: why this is true?

new RegExp('^[a-z]+$', 'i').test('B')

apparently 'B' is out of [a-z]?

like image 681
marstone Avatar asked Dec 09 '22 18:12

marstone


2 Answers

Yes, but you have the i parameter which tells the regex to ignore case.

From the MDN documentation for RegEx:

Parameters

pattern

The text of the regular expression.

flags

If specified, flags can have any combination of the following values:

...

  • i

    ignore case

like image 197
Justin Ethier Avatar answered Dec 11 '22 11:12

Justin Ethier


It's defining a class, which is to say [a-z] is symbolic of "any character, from a to z."

Regex is, by nature, case SensAtiVe as well, so [a-z] varies from [A-Z] (unless you use the i (case insensitive) flag, like you've demonstrated).

e.g.

/[a-z]/              -- Any single character, a through z
/[A-Z]/              -- Any single uppercase letter, A through Z
/[a-zA-Z]/           -- Any single upper or lowercase letter, a through z
/[a-z]/i or /[A-Z]/i -- (note the i) Any upper or lowercase letter, a through z
like image 22
Brad Christie Avatar answered Dec 11 '22 10:12

Brad Christie