How to Reliably Detect Emojis in JavaScript
Inspecting user input for emojis can be challenging in JavaScript. This article explores a robust solution using regular expressions and Unicode property escapes.
Detecting Emojis Using Unicode Properties
Modern browsers support Unicode property escapes, allowing you to match characters based on their Unicode categories. For emojis, the escape sequence to match is:
\p{Emoji}
This matches characters belonging to the Emoji Unicode category.
Excluding Numeric Emojis
By default, the above pattern also matches characters like "123456789#*" which are officially classified as emojis. To exclude these, use the Extended_Pictographic property escape:
\p{Extended_Pictographic}
This matches characters typically understood as emojis, excluding numeric and other symbols.
Example Code:
<code class="javascript">// Test matches with different input console.log( /\p{Emoji}/u.test('flowers'), // false :) /\p{Emoji}/u.test('flowers ???'), // true :) /\p{Emoji}/u.test('flowers 123'), // true :( ); // Test with Extended_Pictographic property escape 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>
Note: Use the u flag at the end of the regular expression to ensure Unicode support.
The above is the detailed content of Here are a few title options, playing with different question structures: **Direct and Concise:** * **How to Detect Emojis in JavaScript with Unicode Property Escapes?** * **Want to Reliably Detect. For more information, please follow other related articles on the PHP Chinese website!