1

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 pass
  • b should pass
  • ab should fail
  • aa should fail
  • abcdefg should fail

You 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.

theJuls
  • 6,788
  • 14
  • 73
  • 160
  • 1
    Possible duplicate of [Match whole string](https://stackoverflow.com/questions/6298566/match-whole-string) – qwermike Dec 06 '18 at 17:44

1 Answers1

6

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:

  • a-z
  • {
  • }
  • 1.

I think you meant [a-z]{1}, which as previously noted is equivalent to [a-z].