【发布时间】:2020-07-27 12:35:34
【问题描述】:
所以我试图在字符串中查找和替换表情符号。到目前为止,这是我使用正则表达式的方法。
const replaceEmojis = function (string) {
String.prototype.regexIndexOf = function (regex, startpos) {
const indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
// generate regexp
let regexp;
try {
regexp = new RegExp('\\p{Emoji}', "gu");
} catch (e) {
//4 firefox <3
regexp = new RegExp(`(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])`, 'g');
}
// get indices of all emojis
function getIndicesOf(searchStr, str) {
let index, indices = [];
function getIndex(startIndex) {
index = str.regexIndexOf(searchStr, startIndex);
if (index === -1) return;
indices.push(index);
getIndex(index + 1)
}
getIndex(0);
return indices;
}
const emojisAt = getIndicesOf(regexp, string);
// replace emojis with SVGs
emojisAt.forEach(index => {
// got nothing here yet
// const unicode = staticHTML.charCodeAt(index); //.toString(16);
})
这样做的问题是我只得到一个带有索引的数组,其中表情符号在字符串中。但是只有这些索引我无法替换它们,因为我不知道它们占用了多少(UTF-16)字节。 为了替换它们,我需要知道我要替换的是什么表情符号。
那么,有没有办法同时获得表情符号的长度?还是有比我更好(也许更简单)的方式来替换表情符号?
【问题讨论】:
-
您认为表情符号到底是什么?有成千上万这样的东西。你的目标是什么?
-
@Brad 我的意思是所有Emojis in Unicode 包括肤色,基本上是您使用
/\p{Emoji}/gu表达式选择的所有内容。我想用表情符号的 SVG 替换它们。这个想法是找到一个表情符号,获取它的 unicode(不是 charcode)并用 SVG 替换它。然而,一个(长)unicode 会使用多个 UTF-16 字符代码进行编码,因此表情符号是各种 UTF-16 字符长,所以我需要知道一个表情符号要替换它的“长度”。
标签: javascript regex unicode emoji