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), ' ');
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'));
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With