Emmanuel Akinfulubi

JavaScriptRegular expressions

Check if a string starts with a capital letter in JavaScript

Beginner · 3 min read

Does a name start with a capital letter? Sign-up forms ask this about names, style checkers ask it about sentences, and code tools ask it about class names. It is also the gentlest possible first step into regular expressions, the small pattern language JavaScript uses to search and check text.

In this tutorial you will write the check three ways: a short pattern for English letters, a pattern that understands every alphabet, and a version with no pattern at all. You only need to know what a function and a string are.

What a regular expression is

A regular expression (people say "regex") is a description of what some text should look like. In JavaScript you write it between two slashes, and its test method answers true or false:

JavaScript

console.log(/bus/.test('the bus is late')); // true
console.log(/bus/.test('the train'));       // false

/bus/ means "the letters b, u, s, one after another, anywhere in the text".

Two building blocks: [A-Z] and ^

Square brackets make a character class: "any one of these characters". [A-Z] is any one capital letter from A to Z. The dash between them means "everything from A to Z".

The caret ^ is an anchor. It does not match a character. It means "the very start of the text". So ^[A-Z] reads as "at the start, one capital letter".

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

1 Does the string start with a capital letter?

easy

Test whether the first character of a string is uppercase.

Stuck? Three hints, smallest first
  1. 1. /^[A-Z]/ anchors to the start with ^.
  2. 2. [A-Z] covers English only. À, Ć and Ж are uppercase too.
  3. 3. A general test is c === c.toUpperCase() && c !== c.toLowerCase().

Step 1: the English-only check

Put the two blocks together inside a function:

Step 1

const startsUpperAscii = (text) => /^[A-Z]/.test(text);
console.log(startsUpperAscii('Lagos')); // true
console.log(startsUpperAscii('lagos')); // false
console.log(startsUpperAscii('9ja'));   // false
console.log(startsUpperAscii(''));      // false

A digit is not in [A-Z], and an empty string has no first character at all, so both give false.

Step 2: why the ^ matters

The natural wrong turn is to leave the anchor out:

JavaScript

const noAnchor = (text) => /[A-Z]/.test(text);
console.log(noAnchor('lagos City')); // true, but it starts with a small l

Without ^, the pattern is happy to find a capital anywhere. The anchor also explains this result:

JavaScript

console.log(/^[A-Z]/.test(' Lagos')); // false

The very first character is a space, not a capital. If your input might have spaces in front, trim it first.

Step 3: names from the rest of the world

[A-Z] only knows the 26 English capitals. É, Ж and Ć are capital letters too, and the English-only check turns them away:

JavaScript

const startsUpperAscii = (text) => /^[A-Z]/.test(text);
console.log(startsUpperAscii('Étienne')); // false, but É is a capital

A name field guarded by this check would refuse real people. Regular expressions have a fix called a Unicode property escape. \p{Lu} means "an uppercase letter in any script". It only works when you add the u flag after the closing slash:

Step 3

const startsUpperUnicode = (text) => /^\p{Lu}/u.test(text);
console.log(startsUpperUnicode('Étienne')); // true
console.log(startsUpperUnicode('Жуков'));   // true
console.log(startsUpperUnicode('étienne')); // false

Lower-case letters are still refused, so the check keeps its meaning.

Step 4: the same check with no regex

What does "upper case" really mean? A character is upper case when it equals its own upper-cased form and is different from its lower-cased form. The second part is what rules out digits and symbols, which look the same in both:

Step 4

function startsUpperPlain(text) {
  const first = [...text][0];
  if (first === undefined) return false;
  return first === first.toUpperCase() && first !== first.toLowerCase();
}
console.log(startsUpperPlain('Étienne')); // true
console.log(startsUpperPlain('9'));       // false: '9' has no lower case
console.log(startsUpperPlain(''));        // false

[...text][0] spreads the string into real characters before taking the first one. Plain text[0] would cut some emoji and rare characters in half.

The full solution

The panel has all three versions and runs them over the same list of words, so you can compare them line by line. Press Run. The checks show the plain and Unicode versions always agree, and where the English-only one falls short.

The answer

// English letters only.
const startsUpperAscii = (text) => /^[A-Z]/.test(text);

// Any script, using Unicode property escapes. The u flag is required.
const startsUpperUnicode = (text) => /^\p{Lu}/u.test(text);

// No regex at all. Works for any letter, and shows what the test really means:
// a character that has a distinct lower-case form and is already in upper case.
function startsUpperPlain(text) {
  const first = [...text][0];                 // spread, so an astral character stays whole
  if (first === undefined) return false;
  return first === first.toUpperCase() && first !== first.toLowerCase();
}

const cases = ['Lagos', 'lagos', '\u00c9tienne', '\u00e9tienne', '\u0416ukov', '9ja', ' Lagos', '', '\u20a6500'];

for (const t of cases) {
  console.log(JSON.stringify(t).padEnd(10),
    'ascii:', String(startsUpperAscii(t)).padEnd(6),
    'unicode:', String(startsUpperUnicode(t)).padEnd(6),
    'plain:', startsUpperPlain(t));
}

Output


      
13 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 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test('a capital passes', startsUpperAscii('Lagos'), true);
test('lower case fails', startsUpperAscii('lagos'), false);
test('a digit fails', startsUpperAscii('9ja'), false);
test('a leading space fails, because ^ means the very start', startsUpperAscii(' Lagos'), false);
test('an empty string fails', startsUpperAscii(''), false);
test('a currency symbol fails', startsUpperAscii('\u20a6500'), false);
test('the ASCII version misses an accented capital', startsUpperAscii('\u00c9tienne'), false);
test('the Unicode version catches it', startsUpperUnicode('\u00c9tienne'), true);
test('and Cyrillic too', startsUpperUnicode('\u0416ukov'), true);
test('while still rejecting lower case', startsUpperUnicode('\u00e9tienne'), false);
test('the plain version agrees with the Unicode one everywhere', cases.every((t) => startsUpperPlain(t) === startsUpperUnicode(t)), true);
test('and disagrees with the ASCII one', cases.some((t) => startsUpperPlain(t) !== startsUpperAscii(t)), true);
test('a digit has no case, so the plain test rejects it', startsUpperPlain('9'), false);

/^[A-Z]/ is the expected answer and it is wrong for most of the world. É, Ж and Ć are capital letters that [A-Z] does not contain, so a name field guarded by it rejects real names. /^p{Lu}/u means "an uppercase letter in any script" and needs the u flag to work at all.

The regex-free version is worth understanding because it says what the question actually means: a character is upper case if it equals its own upper-cased form and differs from its lower-cased form. The second half is what excludes digits and punctuation, which are equal to both. Note [...text][0] rather than text[0], so a character outside the basic range is not split in half.

Common mistakes

  • Forgetting the ^. Without it, 'lagos City' passes because a capital appears later on.
  • Leaving off the u flag. Without u, \p{Lu} does not mean "uppercase letter" at all, so the check stops working.
  • Only testing English names. [A-Z] looks fine until someone called Étienne signs up. Test with an accented name.

Try it yourself

  1. Write startsLower(text) that checks for a lower-case first letter. (Hint: \p{Ll}.)
  2. Make your check ignore spaces at the start, so ' Lagos' passes. Use trim() before testing.
  3. Write allCapitals(text) that checks every word starts with a capital, so 'New York' passes and 'New york' fails.

Keep practising

Newsletter

New writing, when it lands.

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