关闭。这个问题是opinion-based .它目前不接受答案。
想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.
2年前关闭。
Improve this question
替换文本的最有效方法是什么,例如 :) -> 😊。
所以,假设我有一个像“你好 :) 我的名字是亚历克斯”这样的文本。
我应该将文本转换为“你好😊我的名字是亚历克斯”
我在 lodash 实用程序库的帮助下解决了这个问题。
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;
}), ' ');
};
必须有更好的方法来做到这一点。也许使用正则表达式?
短期返回
return _.join(_.map(_.split(string, ' '), s => _.includes(emojis, s) ? emojiMap[s] : s), ' ');
最佳答案
我会通过取键来构建一个模式,escaping所有特殊字符,并通过 |
加入.然后通过在对象上查找匹配的字符串来替换:
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'));
关于javascript - 用表情符号替换字符串的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987323/