Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readJavaScript

RegExp v flag for subtraction and intersection

Write character classes with the v flag to subtract a Unicode set or keep the characters that two sets share.

You need a pattern for letters outside ASCII. Start with \p{Letter} and subtract \p{ASCII} inside one character class using the v flag.

Subtract ASCII from the set of letters

Read -- from left to right. Start with the set on the left, then remove anything in the set on the right. The V8 guide calls this a set difference.

const nonAsciiLetter = /^[\p{Letter}--\p{ASCII}]$/v

for (const value of ['A', 'é', 'π', '7']) {
  console.log(value, nonAsciiLetter.test(value))
}

The results are false, true, true and false in that order. The digit 7 can't survive the subtraction because it wasn't in the starting set. The anchors make this example check a single matching code point against the whole input.

Intersect letters with ASCII

Swap -- for && to keep the overlap. A match must belong to both sets.

const asciiLetter = /^[\p{Letter}&&\p{ASCII}]$/v

for (const value of ['A', 'é', 'π', '7']) {
  console.log(value, asciiLetter.test(value))
}

This version prints true for A and false for the other inputs. The digit qualifies as ASCII but fails the letter condition.

diagram

Membership in two character sets

A belongs to both sets, while é and π belong to the letter set outside ASCII.

The same approach is useful with script properties. Combine a script property with \p{Letter} when you need the overlap and want to keep digits and symbols out. Try a known letter and a symbol from the same script before adding the pattern to a validator.

Check where the pattern will run

The v flag enables Unicode sets. JavaScript rejects a pattern that combines u and v. An engine without v support rejects a regex literal using the flag when it parses the file.

If you ship to mixed runtimes, construct the regex with new RegExp inside a try block so you can catch the syntax error and choose a fallback. Double the backslashes in a plain JavaScript string. Check support in the oldest runtime your app targets.