marstone
marstone

Reputation: 704

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]?

Upvotes: 4

Views: 135

Answers (4)

user1637281
user1637281

Reputation:

Summary

  • The [a-z] means a character set containing characters a-z.

  • The ^ is an anchor which means the set must begin with the first character of input.

  • The + means you must match on one or more from the character set.

  • The $ is an end anchor meaning the set must end the last character of input.

  • The i means to ignore case on your input letters.

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

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

Upvotes: 3

Justin Ethier
Justin Ethier

Reputation: 134177

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

Upvotes: 10

Denys Séguret
Denys Séguret

Reputation: 382160

It means any character between a and z.

As you specified the i flag (case insensitive), it contains also B.

The whole regexp checks that the string contains at least one character and that all characters are in a-z or A-Z.

You can check that new RegExp('^[a-z]+$', 'i').test('B') returns true.

Upvotes: 0

Related Questions