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.
3 Answers
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.
-
do you know if there is much of a difference between regex.test(string) and string.match(regex)? Jun 18, 2010 at 21:29
-
-
3
-
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 allowsa
,a-a
,a-a-a
, and so on (usinga
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. onlya
ora-a
). Oct 8, 2015 at 13:50
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().
-
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 ofregex.test(string)
orstring.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
The answer that accepts empty string:
/^[a-zA-Z]*$/.test('something')
the *
means 0 or more occurrences of the preceding item.