UNPKG

emoji-contextualizer

Version:

Emoji Contextualizer is a lightweight and customizable JavaScript library that replaces specific words or phrases in a string with contextually appropriate emojis. Perfect for chat applications, social media, or fun text transformations.

75 lines (66 loc) 2.27 kB
class EmojiContextualizer { constructor(customMapping = {}) { // Default emoji mapping this.emojiMapping = { "❤️": ["love", "heart"], "😂": ["laugh", "funny", "lol", "laughing"], "🍕": ["pizza", "food"], "😎": ["cool", "style"], }; // Add custom mappings for (const [emoji, keywords] of Object.entries(customMapping)) { if (this.emojiMapping[emoji]) { // Append new keywords to existing emoji this.emojiMapping[emoji] = [ ...new Set([...this.emojiMapping[emoji], ...keywords]), ]; } else { // Add new emoji with its keywords this.emojiMapping[emoji] = keywords; } } } contextualize(inputText, replace = true) { if (!inputText || typeof inputText !== "string") { throw new Error("Input must be a non-empty string."); } const originalText = inputText; let modifiedText = inputText; const foundEmojis = {}; const emojiMapping = { ...this.emojiMapping }; const replaceType = replace ? "replace" : "append"; // Loop through mapping and replace matches with emojis for (const [emoji, keywords] of Object.entries(this.emojiMapping)) { const regex = new RegExp(`\\b(${keywords.join("|")})\\b`, "gi"); // Word boundaries and case-insensitive const matches = RegExp(regex).exec(modifiedText); // Find matches if (matches) { if (replace) { // Replace the found word with emoji modifiedText = modifiedText.replace(regex, `${emoji} `); // Add space after each emoji } else { // Append emoji after the found word modifiedText = modifiedText.replace( regex, (match) => `${match} ${emoji} ` ); } // Record the found emojis and associated keywords foundEmojis[emoji] = [ ...new Set( (foundEmojis[emoji] || []).concat( matches.map((m) => m.toLowerCase()) ) ), ]; } } return { originalText, modifiedText, foundEmojis, emojiMapping, replaceType, }; } } module.exports = EmojiContextualizer;