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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.