JavaScript RegExp u Modifier

The RegExp u modifier in JavaScript, which came into existence at ECMAScript 2015 (ES6), makes it possible to have full support for Unicode in regular expressions. This means that emoji or other characters outside of the 16-bit range as well as symbols and scripts beyond the Basic Multilingual Plane (BMP) can be processed correctly by regex operations, the reason why regex matching becomes more accurate and comprehensive for international text is because the u modifier ensures that patterns are interpreted as Unicode code points rather than UCS-2 code units.

Syntax

/regexp/u

or

new RegExp("regexp", "u")

Example 1: The given below example matches a character outside the BMP with u modifier.

JavaScript
function example() {
    let str1 = "A smiling face: ?";
    let regex = /\u{1F60A}/u;
    let match = str1.match(regex);
    
    console.log("Match found: " + match);
}
example();

Output
Match found: ?

Example 2: The given below example demonstrates how to use the u flag correctly.

JavaScript
function example() {
    let str1 = "A smiling face: ?";
    
    let regexWithoutU = /\u{1F60A}/;
    let matchWithoutU = str1.match(regexWithoutU);
    console.log("Without 'u' modifier: " + matchWithoutU);
    
    let regexWithU = /\u{1F60A}/u;
    let matchWithU = str1.match(regexWithU);
    console.log("With 'u' modifier: " + matchWithU);
}
example();

Output
Without 'u' modifier: null
With 'u' modifier: ?

Supported Browsers

The RegExp u Modifier is supported by the following browsers-

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Microsoft Edge