RegExp v Flag Enables Unicode Set Operations

Use the RegExp v flag to subtract and intersect Unicode character sets, combine script properties, and validate identifiers with set notation.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
// RegExp with the v flag supports subtraction and intersection in classes.
const nonGreekLetters = /[\p{Letter}--\p{Script=Greek}]+/gv;
const greekOrCyrillic = /[\p{Script=Greek}\p{Script=Cyrillic}]+/gv;
const asciiPunctuation = /[\p{Punctuation}&&\p{ASCII}]+/gv;

const sample = "Ωμέγα 42 Привет!?";

console.log("non-greek letters:", sample.match(nonGreekLetters));
console.log("scripts:", sample.match(greekOrCyrillic));
console.log("ascii punctuation:", sample.match(asciiPunctuation));

const identifier = /^[\p{Letter}\p{Number}_]+$/v;
for (const value of ["abc_123", "abc-123"]) {
  console.log(value, identifier.test(value));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

non-greek letters: [ 'Привет' ]
scripts: [ 'Ωμέγα', 'Привет' ]
ascii punctuation: [ '!?' ]
abc_123 true
abc-123 false

How the snippet works

The one repetition in this snippet is the loop for (const value of ["abc_123", "abc-123"]).

Everything operates on top-level bindings: nonGreekLetters, greekOrCyrillic, asciiPunctuation, sample.

Caveats

  • Nothing to install: the snippet stays inside the standard library.

Applying it

Expect labeled output — non-greek letters:, scripts:, ascii punctuation: — when the file runs.

Statements that matter

const greekOrCyrillic = /[\p{Script=Greek}\p{Script=Cyrillic}]+/gv;
const nonGreekLetters = /[\p{Letter}--\p{Script=Greek}]+/gv;
const asciiPunctuation = /[\p{Punctuation}&&\p{ASCII}]+/gv;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `nonGreekLetters`, `greekOrCyrillic`, `asciiPunctuation`.