Home > Web Front-end > JS Tutorial > body text

How can I reliably detect and identify emojis in JavaScript using regular expressions?

Patricia Arquette
Release: 2024-10-25 03:30:29
Original
992 people have browsed it

How can I reliably detect and identify emojis in JavaScript using regular expressions?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!