js match emoticon

Matching Emoticons using JavaScript

If you ever wondered how to match emoticons in JavaScript, you are not alone. Emoticons are a popular way of expressing emotions in text-based conversations, and being able to recognize them can be useful for various purposes such as sentiment analysis or simply for displaying them properly on your website.

Method 1: Regular Expressions

One way to match emoticons is by using regular expressions. A regular expression is a pattern that specifies a set of matching strings. In the case of emoticons, we can use a regular expression to match a specific sequence of characters that represent the emoticon.


const text = "I love ❤️ coding!";
const emoticonRegex = /[\u{1F601}-\u{1F64F}]/gu;
const emoticons = text.match(emoticonRegex);
console.log(emoticons); // ["❤️"]

In this example, we define a regular expression that matches any Unicode character that falls within the range of emoticons (from \u{1F601} to \u{1F64F}). We then use the match() method to search for all occurrences of the emoticons in the text.

Method 2: Map Matching

Another way to match emoticons is by using a map that stores the emoticons as keys and their corresponding Unicode values as values.


const text = "I love ❤️ coding!";
const emoticonMap = new Map([
  ["❤️", "\u{2764}\u{FE0F}\u{200D}\u{1F680}"],
  ["😂", "\u{1F602}"]
]);
const emoticons = [];
for (const [emoticon, unicode] of emoticonMap) {
  if (text.includes(emoticon)) {
    emoticons.push(unicode);
  }
}
console.log(emoticons); // ["❤️"]

In this example, we define a map that stores the emoticons and their corresponding Unicode values. We then iterate over the map and check if the text contains the emoticon. If it does, we add its Unicode value to the list of emoticons.

Conclusion

Matching emoticons in JavaScript can be done in several ways, depending on your specific needs. Using regular expressions is a fast and efficient way to match emoticons, while using a map allows for more customization and control over the matching process.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe