@babel/plugin-transform-unicode-sets-regex

unicode-sets-regex - 图1info

This plugin is included in @babel/preset-env, in ES2024

This plugin transforms regular expressions using the v flag, introduced by the RegExp set notation + properties of strings proposal, to regular expressions that use the u flag.

It only transforms /.../v syntax and it does not patch the new RegExp constructor, since its arguments cannot be pre-transformed statically: to handle runtime behavior of functions/classes, you will need to use a polyfill instead.

Example

Intersection

input.js

  1. /[\p{ASCII}&&\p{Decimal_Number}]/v;

will be transformed to

output.js

  1. /[0-9]/u;

Difference

input.js

  1. // Non-ASCII white spaces
  2. /[\p{White_Space}--\p{ASCII}]/v;

will be transformed to

output.js

  1. /[\x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/u;

Property of Strings

input.js

  1. /^\p{Emoji_Keycap_Sequence}$/v.test("*\uFE0F\u20E3");
  2. // true

will be transformed to

output.js

  1. /^(?:\*️⃣|#️⃣|0️⃣|1️⃣|2️⃣|3️⃣|4️⃣|5️⃣|6️⃣|7️⃣|8️⃣|9️⃣)$/u.test("*\uFE0F\u20E3");
  2. // true

Here is a list of supported properties. Note that using property of strings with u-flag will error.

input.js

  1. /\p{Emoji_Keycap_Sequence}/u;
  2. // Error: Properties of strings are only supported when using the unicodeSets (v) flag.

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-unicode-sets-regex
  1. yarn add --dev @babel/plugin-transform-unicode-sets-regex
  1. pnpm add --save-dev @babel/plugin-transform-unicode-sets-regex

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-unicode-sets-regex"]
  3. }

Via CLI

Shell

  1. babel --plugins @babel/plugin-transform-unicode-sets-regex script.js

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-unicode-sets-regex"],
  3. });