Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to replace string with emoji [closed]

What is the most efficient way to replace text like :) -> 😊.

So, assume I have a text like "Hello :) my name is Alex". I should convert the text into "Hello 😊 my name is Alex"

I solved this issue with help of lodash utility library.

const replaceStringWithEmoji = (string) => {
  const emojiMap = {
    ':)': '😊',
    ':(': '🙁',
    ':D': '😁',
    ';(': '😥',
    ':O': '😮',
    ';)': '😉',
    '8)': '😎',
    '>:@': '😡',
  };

  const emojis = [...Object.keys(emojiMap)];
  return _.join(_.map(_.split(string, ' '), (s) => {
    if (_.includes(emojis, s)) {
      return emojiMap[s];
    }
    return s;
  }), ' ');
};

There has to be a better way of doing it. Maybe with Regex?

Short return

 return _.join(_.map(_.split(string, ' '), s => _.includes(emojis, s) ? emojiMap[s] : s), ' '); 
like image 904
Alex Avatar asked Dec 23 '22 21:12

Alex


2 Answers

I'd construct a pattern by taking the keys, escaping all the special characters, and joining by |. Then replace by looking up the matched string on the object:

const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

const replaceStringWithEmoji = (string) => {
  const emojiMap = {
    ':)': '😊',
    ':(': '🙁',
    ':D': '😁',
    ';(': '😥',
    ':O': '😮',
    ';)': '😉',
    '8)': '😎',
    '>:@': '😡',
  };
  const pattern = new RegExp(
    Object.keys(emojiMap).map(escape).join('|'),
    'g'
  );
  return string.replace(pattern, match => emojiMap[match]);
};

console.log(replaceStringWithEmoji('foo :) bar'));
console.log(replaceStringWithEmoji('foo :) bar 8) baz'));
like image 175
CertainPerformance Avatar answered Dec 25 '22 09:12

CertainPerformance


You don't need to change your emojiMap to array you can build a regex with alternation and use repalce

const replaceStringWithEmoji = (string) => {
  const emojiMap = {
    ':)': '😊',
    ':(': '🙁',
    ':D': '😁',
    ';(': '😥',
    ':O': '😮',
    ';)': '😉',
    '8)': '😎',
    '>:@': '😡',
  };
  let regex = /(?::\)|:\(|:D|;\(|:O'|;\)|8\)|>:@)/g
  return string.replace(regex,(m)=>emojiMap[m] || m)
};

console.log(replaceStringWithEmoji("Hello :) my name is Alex"))
like image 40
Code Maniac Avatar answered Dec 25 '22 10:12

Code Maniac