-3
/^[a-zA-Z]+$/ 

vs

/[^a-zA-Z]+$/
nicael
  • 16,503
  • 12
  • 50
  • 80

3 Answers3

2

The ^ at the start of the expression means "Anchor at the beginning of the string".

The ^ inside the character class [] expression means negate.

So /^[a-zA-Z]$/ matches a string that consists entirely (from beginning to end) of upper case and lower case alphabetic characters, while /[^a-zA-Z]$/ matches the "end of the string that does not consist of alphabetic characters" (for example, numbers at the end of the string).

this is a string       -- matches neither 
                          (contains non alphabetic, but doesn't end in it)

this is a number: 123  -- second expression matches ': 123'
                          (string ends in non-alphabetic characters)

this                   -- first expression matches  'this' 
                          (string contains only alphabetic characters)
Floris
  • 43,828
  • 5
  • 63
  • 112
0

In case 1 the ^ indicates the beginning of the input. Case two negates the term.

Case 1: From beginning(^) to end ($) match a-zA-Z 0 or more(+) times

Case 2: Match everything that does not(^) end($) with a-zA-Z 0-x(+) chars

Fonzy
  • 641
  • 3
  • 14
0

/^[a-zA-Z]+$/

means that the string should
^: start with
[a-zA-Z]: lower case or upper case alpha character
+: At least one of the previous, in this case at least one of alpha character
$: Should end with a uppper case or lower case alpha character

Exmaple:
OnLyUpPeRaNdLoWeRcAsEaNdNoSpAcEs

/[^a-zA-Z]+$/

[^a-zA-Z]: NOT an upper case or lower case character
+: At least one of the previous, in this case at least one character but NOT of upper case or lower case alpha character
$: Should end with a none upper case or lower case alpha character

Example:
123456789
anything12345 <-- this works because we didn't specify how the string should start but we know that it should end with a non alpha character

CMPS
  • 7,505
  • 4
  • 26
  • 49
  • /^[a-zA-Z]+$/.test('AbRcD'); console --> true /[^a-zA-Z]+$/.test('Abf3498'); console --> true – user3475797 Jun 07 '14 at 14:07
  • @user3475797 yes that's true because we didn't specify how the second expression starts unlike the first expression – CMPS Jun 07 '14 at 14:08