Ben Ben - 2 months ago 21
Javascript Question

javascript regex for alphabetical range, for instance AF-BC

I'm trying to use javascript to check if a two-character string is in a certain alphabetical range. If the range would be AF to AZ i could use:

var regAfAz = /^[a][f-z]/i;


But what if the range would be for example AF to BH? So far, all i can think of is splitting the variable and use:

var regAfAz = /^[a][f-z]/i;
var regBaBh = /^[b][a-h]/i;


to check it twice, but that seems rather unhandy. Any ideas?

Answer

You're looking for something like this:

var reg = /(a[f-z]|b[a-h])/i;

console.log(reg.test('ab'));
console.log(reg.test('ay'));
console.log(reg.test('bc'));
console.log(reg.test('bz'));