javascript regex : only english letters allowed

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

The answer that accepts empty string:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyodaView Question on Stackoverflow
Solution 1 - Javascriptmeder omuralievView Answer on Stackoverflow
Solution 2 - JavascriptShawn MooreView Answer on Stackoverflow
Solution 3 - JavascriptNorman LinView Answer on Stackoverflow