Emmanuel Akinfulubi

JavaScriptRegular expressions

Allow only letters, dashes and underscores in JavaScript

Beginner · 3 min read

Usernames, URL slugs and file names often follow one rule: letters, dashes and underscores only. lagos-abuja and bus_route pass, has space and has.dot don't. Social sites use it for handles, blogs use it for post addresses, and build tools use it for project names.

This tutorial writes that check, and on the way teaches the one detail about character classes that trips up almost everyone: where you put the dash. At the end you will write a stricter slug rule that refuses -leading, trailing- and double--dash. You need to know /.../.test(), ^, $ and +. The rest is explained as we go.

The dash inside a class

In a character class, a dash between two characters makes a range. [a-c] doesn't mean "a, dash, c". It means "a, b or c":

JavaScript

console.log(/^[a-c]$/.test('b')); // true: b is in the range
console.log(/^[a-c]$/.test('-')); // false: the dash isn't in it

To match a real dash, put it first or last in the class, or escape it with a backslash:

JavaScript

console.log(/^[a-z-]+$/.test('a-b'));  // true: dash last, so it's literal
console.log(/^[a\-c]+$/.test('b'));    // false: escaped, so only a, -, c

Getting this wrong rarely shows an error. The class just matches more, or less, than you meant.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

20 Letters, dashes and underscores

easy

Check for a value made of letters, dashes and underscores — the shape of a slug or a handle.

Stuck? Three hints, smallest first
  1. 1. Inside a character class, a dash must be first or last, or escaped, or it means a range.
  2. 2. [a-z-_] works because the dash is at the end; [a-_z] is an error.
  3. 3. Decide whether it must contain all three, or only be made of them.

Step 1: made of letters, dashes and underscores

Put letters, the underscore and the dash in one class, with the dash last. The i flag lets capitals through:

Step 1

const ONLY = /^[a-z_-]+$/i;
console.log(ONLY.test('lagos-abuja')); // true
console.log(ONLY.test('lagos_abuja')); // true
console.log(ONLY.test('UPPER-CASE'));  // true
console.log(ONLY.test('has space'));   // false
console.log(ONLY.test('has.dot'));     // false
console.log(ONLY.test('123'));         // false: no digits allowed
console.log(ONLY.test(''));            // false

^ and $ make the whole string follow the rule, and + means at least one character, so the empty string fails.

Step 2: a second way to read the question

"Letters, dashes and underscores" could also mean the value must contain at least one of each. That is a different question with different answers:

Step 2

const hasAll = (value) => /[a-z]/i.test(value) && value.includes('-') && value.includes('_');
console.log(hasAll('lagos-abuja')); // false: no underscore
console.log(hasAll('bus-route_x')); // true

Each part checks one thing, joined with && ("and"). When a rule can be read two ways, pick one, write a test that pins it down, and the doubt goes away. The answer has both versions.

Step 3: the wrong turn for slugs

For a slug, the part of a URL like /blog/lagos-abuja, the first class isn't strict enough:

JavaScript

const ONLY = /^[a-z_-]+$/i;
console.log(ONLY.test('-leading'));     // true
console.log(ONLY.test('double--dash')); // true

A slug shouldn't start or end with a dash, or have two in a row.

Step 4: let the shape forbid bad separators

Describe a slug as "a word, then any number of groups of a separator followed by a word". A word here is [a-z0-9]+, lower-case letters and digits. A separator is [-_], one dash or underscore. (?: ... ) groups without capturing, and * means "zero or more times":

Step 4

const SLUG = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;
console.log(SLUG.test('lagos-abuja'));   // true
console.log(SLUG.test('lagos_abuja_1')); // true
console.log(SLUG.test('route-9ja'));     // true
console.log(SLUG.test('-leading'));      // false
console.log(SLUG.test('trailing-'));     // false
console.log(SLUG.test('double--dash'));  // false
console.log(SLUG.test('UPPER-CASE'));    // false

Every separator must have a word on both sides, so the three bad shapes can't match. There is no i flag, so capitals are refused, which keeps addresses consistent. This version allows digits, because slugs often contain them.

The full solution

The panel runs a list of values through all three checks: made of the allowed characters, contains all three, and valid slug. Press Run and compare the columns for lagos-abuja and double--dash.

The answer

// Made of letters, dashes and underscores. The dash is LAST in the class, so it
// is a literal dash and not a range.
const ONLY = /^[a-z_-]+$/i;

// Contains at least one of each, which is a different question the title allows.
const hasAll = (value) => /[a-z]/i.test(value) && value.includes('-') && value.includes('_');

// A realistic slug rule: lower case, no leading or trailing separator, no doubles.
const SLUG = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;

const cases = ['bus-route_1', 'lagos-abuja', 'lagos_abuja', 'plain', 'has space',
  'has.dot', 'UPPER-CASE', '-leading', 'trailing-', 'double--dash', '', '123'];

for (const v of cases) {
  console.log(JSON.stringify(v).padEnd(14),
    'only:', String(ONLY.test(v)).padEnd(6),
    'has all three:', String(hasAll(v)).padEnd(6),
    'valid slug:', SLUG.test(v));
}
console.log('--- the dash position matters ---');
console.log('[a-z-_] : dash at the end is literal ->', /^[a-z-_]+$/.test('a-b_c'));
console.log('[a-c] is a RANGE, so it matches b   ->', /^[a-c]+$/.test('b'));
console.log('[a\\-c] escaped is literal, so b fails ->', /^[a\-c]+$/.test('b'));

Output


      
21 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 21 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

21 checks

test('letters, a dash and an underscore pass', ONLY.test('bus-route_1'.replace(/\d/g, '')), true);
test('letters and a dash pass', ONLY.test('lagos-abuja'), true);
test('letters and an underscore pass', ONLY.test('lagos_abuja'), true);
test('letters alone pass', ONLY.test('plain'), true);
test('a space is refused', ONLY.test('has space'), false);
test('a dot is refused', ONLY.test('has.dot'), false);
test('a digit is refused by this class', ONLY.test('123'), false);
test('an empty string is refused', ONLY.test(''), false);
test('upper case passes, because of the i flag', ONLY.test('UPPER-CASE'), true);
test('the "has all three" question is different', hasAll('lagos-abuja'), false);
test('and only bus-route passes it', hasAll('bus-route_x'), true);
test('a dash at the end of a class is a literal dash', /^[a-z-]+$/.test('a-b'), true);
test('while a dash in the middle makes a range', /^[a-c]+$/.test('b'), true);
test('and an escaped dash is literal again', /^[a\-c]+$/.test('b'), false);
test('a good slug passes', SLUG.test('lagos-abuja'), true);
test('with an underscore too', SLUG.test('lagos_abuja_1'), true);
test('a leading separator is refused', SLUG.test('-leading'), false);
test('a trailing separator is refused', SLUG.test('trailing-'), false);
test('a doubled separator is refused', SLUG.test('double--dash'), false);
test('upper case is refused by the slug rule', SLUG.test('UPPER-CASE'), false);
test('digits are allowed in a slug', SLUG.test('route-9ja'), true);

The mechanical lesson is the dash. Inside a character class, - between two characters means a range: [a-c] matches b. To match a literal dash, put it first, put it last, or escape it — the three assertions comparing [a-z-], [a-c] and [a-c] make the difference concrete. Getting this wrong usually produces a class that matches far more than you intended, silently.

The other half is reading the question. "Contains alpha, a dash and an underscore" could mean made only of those, or containing at least one of each. They give different answers for lagos-abuja, so both are implemented. When a specification is ambiguous like this, pick one, write the assertion that pins it down, and the ambiguity stops being a problem.

SLUG is the version you would actually ship: the [a-z0-9]+(?:[-_][a-z0-9]+)* shape makes a leading, trailing or doubled separator unmatchable, which is the same trick as the email local part in exercise 3.

Common mistakes

  • Putting the dash between two characters. [a-_z] reads as a range from a to _, which is backwards, so JavaScript throws a SyntaxError. Keep the dash first or last.
  • Forgetting the anchors. Without ^ and $, any string with one allowed character passes.
  • Checking characters but not the shape. [a-z_-]+ allows ---. For slugs, use the word-separator-word shape.

Try it yourself

  1. Write toSlug(title) that lower-cases a title and replaces each run of spaces with a dash: 'Lagos to Abuja' becomes 'lagos-to-abuja'.
  2. Change SLUG so only dashes are allowed as separators, not underscores.
  3. Limit a username to 3 to 20 characters by adding a length check next to ONLY.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.