Identifying Emojis in JavaScript Using Regex
Detecting emojis in JavaScript can be challenging due to their unicode representation. While previously suggested methods rely on mumeric ranges, this approach is unreliable and inflexible.
Fortunately, modern browsers now support Unicode property escape. This allows for precise matching of emojis by their unicode category. Specifically, the "p{Emoji}" property escape matches all emojis.
However, it's important to note that 0123456789#* and similar characters are officially classified as emojis. To avoid matching these characters, the "p{Extended_Pictographic}" property escape can be used instead, which targets characters typically understood as emojis.
To ensure compatibility, use the "u" flag at the end of the regular expression.
Examples:
<code class="javascript">console.log( /\p{Emoji}/u.test('flowers'), // false :) /\p{Emoji}/u.test('flowers ???'), // true :) /\p{Emoji}/u.test('flowers 123'), // true :( ) console.log( /\p{Extended_Pictographic}/u.test('flowers'), // false :) /\p{Extended_Pictographic}/u.test('flowers ???'), // true :) /\p{Extended_Pictographic}/u.test('flowers 123'), // false :) )</code>
The above is the detailed content of How can I reliably detect and identify emojis in JavaScript using regular expressions?. For more information, please follow other related articles on the PHP Chinese website!