62

Quick question: I need to allow an input to only accept letters, from a to z and from A to Z, but can't find any expression for that. I want to use the javascript test() method.

0

3 Answers 3

140

let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

5
  • do you know if there is much of a difference between regex.test(string) and string.match(regex)? Jun 18, 2010 at 21:29
  • hmm it seems I was missing only the start and end tags, thanks!
    – yoda
    Jun 18, 2010 at 21:38
  • 3
    what about other languages' letters?
    – vsync
    Jan 12, 2015 at 17:11
  • how can you allow punctuation like all letters but also you might have united-states as allowable? Oct 4, 2015 at 4:28
  • @WeDoTDD Like this: ^[a-zA-Z]+(-[a-zA-Z]+)*$. The regular expression accepts at least one English letter, and then naught or more of one dash and at least one letter. That allows a, a-a, a-a-a, and so on (using a to stand for at least one capital or lower-case letter). You can change the asterisk (*) to a question mark (?) if you want to allow at most one dash (e.g. only a or a-a).
    – Toothbrush
    Oct 8, 2015 at 13:50
16

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

3
  • Just to clarify, will this expression return null when there is some other, say, '&' character is present? IF there are only English letters, then it will return the input itself? Jul 23, 2016 at 16:18
  • 1
    @MadPhysicist TLDR; Yes. Explanation: Using string.match(regex) will return null if there are no matches otherwise it returns an array of matched strings. Since this regex is matching everything from the start of the string (^) to the end of the string ($), a match() here will return the whole string or null. See my DEMO above for uses of regex.test(string) or string.match(regex). Jul 24, 2016 at 0:09
  • 1
    @MadPhysicist clarification: match() here actually returns an array with the whole string at the zero index. Jul 24, 2016 at 0:25
5

The answer that accepts empty string:

/^[a-zA-Z]*$/.test('something')

the * means 0 or more occurrences of the preceding item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.