如何将字符串中的所有表情符号替换为unicode JS

How to replace all emoji in string to unicode JS

我无法将字符串中的表情符号替换为具有 unicode 的字符串。

例如:

我有字符串: const str = "My string is with emoji "

我需要将这个字符串转换成 const str = "My string EMOJI UNICODE is with emoji EMOJI UNICODE"

表情符号 unicode 应如下所示:[e-1f60e]。因为我有将带有 unicode 的字符串转换为带有表情符号的字符串的函数:

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, (match, hex) =>
    String.fromCodePoint(Number.parseInt(hex, 16))
  );
}

console.log(convertEmoji('string [e-1f60e] sadfsadfsadf'));  // "string  sadfsadfsadf"

你可以做的是,从 Array.from():

开始
Array.from("My string  is with emoji ")

这会给你单独的字符到一个数组中:

["M", "y", " ", "s", "t", "r", "i", "n", "g", " ", "", " ", "i", "s", " ", "w", "i", "t", "h", " ", "e", "m", "o", "j", "i", " ", ""]

在这里,您可以使用 charCode 函数来检查当前项目是否是表情符号,并使用 .map().

应用您的自定义函数

检查 进行初始转换,并使用 Array.map() 函数进行映射,最后使用 .join("").

将数组转换为字符串

Note: I have explained the process of converting so that the OP can go ahead and try it out, and I intentionally didn't think of spoon-feeding the OP with the complete solution, even though I have got one, tried and tested.

您可以像在您的函数中那样使用 replaceThis answer 为现代 JavaScript 提供了一个匹配各种 "emoji" 范围的正则表达式。然后在回调中,您可以使用 codePointAt 获取表情符号的代码点值,通过 toString(16) 将其转换为十六进制,并 return 所需格式的字符串:

const str = "My string  is with emoji "
const rex = /[\u{1f300}-\u{1f5ff}\u{1f900}-\u{1f9ff}\u{1f600}-\u{1f64f}\u{1f680}-\u{1f6ff}\u{2600}-\u{26ff}\u{2700}-\u{27bf}\u{1f1e6}-\u{1f1ff}\u{1f191}-\u{1f251}\u{1f004}\u{1f0cf}\u{1f170}-\u{1f171}\u{1f17e}-\u{1f17f}\u{1f18e}\u{3030}\u{2b50}\u{2b55}\u{2934}-\u{2935}\u{2b05}-\u{2b07}\u{2b1b}-\u{2b1c}\u{3297}\u{3299}\u{303d}\u{00a9}\u{00ae}\u{2122}\u{23f3}\u{24c2}\u{23e9}-\u{23ef}\u{25b6}\u{23f8}-\u{23fa}]/ug;
const updated = str.replace(rex, match => `[e-${match.codePointAt(0).toString(16)}]`);
console.log(updated);

另见 。 ES2018 添加了 Unicode 属性 转义。但不幸的是,支持仍然参差不齐,尽管他在回答中使用的支持在 Chromium 及其衍生产品(Chrome、Brave、Chromium Edge)和 iOS Safari 中有效,但遗憾的是还没有在 Firefox 中使用。

如果您的目标是 ECMAScript 2018 及更新版本,您可以使用

/\p{Emoji}/ug

JS 演示:

const str = "My string  is with emoji ";
console.log(
  str.replace(/\p{Emoji}/ug, (m, idx) =>
   `[e-${m.codePointAt(0).toString(16)}]`
  )
);