JS: Regex Flag u (unicode)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Flag u

note, flag u is superceded by flag v, since 2024.

u

With flag u on:

parse the regex in unicode mode. e.g. supports Regex Unicode Property pattern \p{unicodeProperty} and Unicode Escape Sequence \u{hexadecimal}.

the text is interpreted as sequence of unicode characters. (i.e. sequence of unicode code points). (otherwise text is 2-byte sequence of UTF-16 encoding) [see JS: String Index and Code Unit]

// unicode property search syntax only work with u
console.assert(
 /\p{Emoji}/u.test("🦋"),
);

console.assert(
 /\p{Emoji}/.test("🦋") === false,
);

Example. regex dot pattern

// Without u. treats emoji as two code units
console.log("🦋".match(/./));
// [ "�", index: 0, input: "🦋", groups: undefined ]

// With u . treats it as one code point
console.log("🦋".match(/./u));
// [ "🦋", index: 0, input: "🦋", groups: undefined ]

Example. match byte sequence

// without u flag. the byte sequence D83E matches the first part of utf16 encoding of the butterfly character.
console.assert(
 /\uD83E/.test("🦋") === true,
);

// with u flag. the butterfly text is considered as one single character. D83E doesn't match anymore.
console.assert(
 /\uD83E/u.test("🦋") === false,
);

// the butterfly character has codepoint 1F98B. searching by that results in match.
console.assert(
 /\u{1F98B}/u.test("🦋"),
);

/*
🦋
Name: BUTTERFLY
Codepoint: 129419
HEXD: 1F98B
UTF8: F0 9F A6 8B
UTF16: D83E DD8B
*/

Example. unicode escape in regex

/* digit 0 has codepoint 48.
It is 30 in hexadecimal.
the unicode escape form
\u{30}
stand for the char 0 in string.
*/
console.assert(
 "\u{30}" === "0",
);

/*
however, in regex literal expression,
/\u{30}/
means the char repeated 30 times.
you need the unicode flag u to interpreted it as digit 0.
/\u{30}/u
*/

// the regex here is interpreted as u repeated 30 times
console.assert(
 /\u{30}/.test("0") === false,
);

console.assert(
 /\u{30}/.test("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu"),
);

// the regex here is interpreted as the character 0, because the flag u
// deno-fmt-ignore
console.assert(
/\u{30}/u.test("0") );

// if you use the regex constructor , you don't have this problem.
console.assert(
 RegExp("\u{30}", "").test("0"),
);

Example. unicode character search without flag u or v

/* replace butterfly emoji by x */

// you don't need the regex flag u to match unicode characters.
console.assert(
 "🦋".replace(/🦋/, "x") === "x",
);

// but in general, you should have it on whenever your string or regex contains non-ascii characters.
console.assert(
 "🦋".replace(/🦋/u, "x") === "x",
);

Regexp.prototype.unicode

RegExp.prototype.unicode is a Getter Property. Value is true if flag u is set, on the given regex object.

// demo RegExp.prototype.unicode
const aa = /some/u;
console.assert(aa.unicode);

const bb = /some/;
console.assert(bb.unicode === false);