Matching Unicode With the u and v Flags

Your branch names now fit under the host’s 32-byte limit. The slug step of the team lead’s Python helper still needs a careful port. It keeps every Unicode letter and number in a title and turns everything else into hyphens. In “Zoë’s 😀 refund fix”, the ë has to stay and the emoji has to go.

In this lesson, you’ll make JavaScript regular expressions ask the Unicode questions the Python script put to unicodedata.

Ask for Letters With \p{L}

Python’s re has no escape for “a letter in any script”. The [^\W\d_] trick comes close but also lets in numbers such as ², so the team lead’s script asks unicodedata.category() about each character instead:

Language: Python
import unicodedata

for char in "Zoë😀":
    print(char, unicodedata.category(char))

Each character has a two-letter general category, and the first letter names its group:

Language: Program Output
Z Lu
o Ll
ë Ll
😀 So

Lu and Ll are uppercase and lowercase letters, and So is “other symbol”. The script keeps a character when its category starts with L or N. Python’s Unicode-aware \w isn’t an exact replacement, because it also matches the underscore.

JavaScript asks the category question inside the pattern. A Unicode property escape such as \p{L} matches any character whose category starts with L, and \p{N} does the same for numbers. A Python str pattern understands Unicode without any flag, and the third-party regex module spells \p{L} exactly this way, so a direct port of a letters-only check has no flag either:

Language: JavaScript
console.log(/^\p{L}+$/.test("Zoë"));

Zoë is three letters. Predict what the check logs, then run it:

Language: Program Output
false

The check fails silently. Test the pattern against its own spelling:

Language: JavaScript
console.log(/^\p{L}+$/.test("p{L}"));

It matches the literal text:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.