yoda
yoda

Reputation: 10981

javascript regex : only english letters allowed

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.

Upvotes: 63

Views: 185456

Answers (3)

meder omuraliev
meder omuraliev

Reputation: 186562

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.

Upvotes: 143

Norman Lin
Norman Lin

Reputation: 483

The answer that accepts empty string:

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

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

Upvotes: 5

Shawn Moore
Shawn Moore

Reputation: 473

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().

Upvotes: 16

Related Questions