[英]What is the most efficient way to find the common words in a String [on hold]
[英]Most efficient way to replace string with emoji [on hold]
替換文本的最有效方法是什么:) - >😊。
所以,假設我有一個文本,如“你好:)我的名字是亞歷克斯”。 我應該將文本轉換為“你好😊我的名字是亞歷克斯”
我在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), ' ');
我通過獲取密鑰, 轉義所有特殊字符並通過|
加入來構建模式 。 然后通過在對象上查找匹配的字符串來替換:
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'));
您不需要將emojiMap更改為數組,您可以使用交替構建正則表達式並使用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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.