JS: Regex Syntax. Unicode Property Escape

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2018)

Each unicode character has many properties. For exmaple, property to indicate what script (writing system) it is, or if it is a letter char, number, punctuation, math symbol ( ± ∑ ∫ ), emoji, Chinese character, or is capital letter etc.

Unicode Property escape allows you to match characters by specifying their unicode properties.

note, the regex object must have flag u on or flag v on.

\p{PropertyName}

match a char that has property name PropertyName.

// get emoji chars
console.log(
 "i ♥ 😸".match(RegExp("\\p{Emoji}", "gu")),
);
// [ "♥", "😸" ]

// get chars that default to emoji presentation. this is a smaller set.
console.log(
 "i ♥ 😸".match(RegExp("\\p{Emoji_Presentation}", "gu")),
);
// [ "😸" ]
// get characters that's unicode letter
// many programing language identifier only allow unicode letter
console.log(
 "ä α ж の ♥ ⠮ 🦋 ∑ ° ⊕ +".match(/\p{L}/gu),
);
// [ "ä", "α", "ж", "の" ]
\p{PropertyName=PropertyValue}

match a char whose PropertyName is PropertyValue

// get Latin chars
console.log(
 "abc ♥ 😸. $_$".match(RegExp("\\p{Script_Extensions=Latin}", "gu")),
);
// [ "a", "b", "c" ]
\P{x}

(Note, uppercase P) Negation of \p{x}.