Dan Dan - 4 months ago 12
Javascript Question

Regular expression to check word and word length

In

JavaScript
I am using the regular expression,
/^([a-z]){3}^(foo)/i
, to try and match a specific word and the words length. The regex should also be case insensitive. So I added an
i
modifier on the end.

What I think this says it should do is

^ : Start at beginning of string
([a-z]){3} : Match [a-z] exactly three times
^ : Go back to start of string
(foo) : Match the word foo exactly


However when I tested this with the following strings
fOo
,
foo
,
Foo
,
FoO
it didn't return any matches.

I would appreciate it if someone could explain what I am doing wrong and help me fix it.

Regex101

Edit for Sukima

Example strings which should work:

fOo
FoO
foo
FOO


Example string which shouldn't work

f o o
adfsFoO
fooFoe
FfOoF
:fdFoo:


The aim of the regex is to check that the string matches the word
foo
exactly and is length of
3
exactly

Ivo Ivo
Answer

Hence foo actually is a subset of your prior regex, the following should do the trick:

/^\w{3})/i

or the following if numbers are not allowed:

/^[a-zA-Z]{3}/i

This regex matches every word of exactly three characters at the beginning of the string (or line if you specify the /m modifier) regardless if its upper- or lowercase.

Edit (responds to comments):

if you need to match the word foo precisely regardless of its case just go for:

/^foo$/i

Example matches: fOo, fOo, foo, Foo, FoO... more available on regex101