Reputation: 7470
Seems quite simple, but I can't find how to do this. I want to match a single character within a certain range, say a to z.
[a-z]
Currently doing the following:
const regex = RegExp('[a-z]');
console.warn('TEST', regex.test('a'))
Simple enough. However I want it to be a single character. If there is any more than one, regardless if they also belong in that range, it needs to fail. So for example:
a
should passb
should passab
should failaa
should failabcdefg
should failYou get the idea.
I have tried some variations such asL
[{1}a-z]
Which doesn't do anything. Ultimately it still accepts any combination of character within that range.
Upvotes: 1
Views: 205
Reputation:
Pin the string down using ^
and $
, which match the "start of string" and the "end of string", respectively.
Your regex would be ^[a-z]$
, which means you expect to match a single character between a
and z
, and that single character must be the entire string to match.
The reason [a-z]{1}
(which is equivalent to [a-z]
) doesn't work is because you can match single characters all along the string. The start/end of the string aren't "pinned down".
let str = ['a','b','ab','aa','abcdefg'];
const regex = /^[a-z]$/;
str.forEach(w => console.warn(w, regex.test(w)));
By the way, [{1}a-z]
doesn't do what you think it does. You intended to match a single alphabetic character, but this adds three more characters to the match list, which becomes:
{
}
1
. I think you meant [a-z]{1}
, which as previously noted is equivalent to [a-z]
.
Upvotes: 6