So I'm trying to find and replace emojis in strings. This is my approach with regexp so far.
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);
})
The problem with this is that I only get an array with indices where the emojis are in the string. But with only these indices I can't replace them because I don't know how many (UTF-16) bytes they take up. Also for replacing them I need to know what emoji it is I am replacing.
So, is there a way to also get the length of the emoji? Or is there a better (perhaps simpler) way than mine to replace emojis?