猿问

用表情符号替换字符串的最有效方法

替换文本的最有效方法是什么:) -> 😊。


所以,假设我有一个类似“你好 :) 我的名字是亚历克斯”的文本。我应该将文本转换为“你好😊我的名字是亚历克斯”


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



心有法竹
浏览 209回答 2
2回答

RISEBY

我会通过获取键,转义所有特殊字符并加入|. 然后通过在对象上查找匹配的字符串来替换: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 更改为数组,您可以使用交替构建正则表达式并使用 repalceconst 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"))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答