简体   繁体   English

用表情符号替换字符串的最有效方法[暂停]

[英]Most efficient way to replace string with emoji [on hold]

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. 我在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;
  }), ' ');
};

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 您不需要将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM