2021-07-04 20:19:04 -07:00
|
|
|
import { getEmojiRegex } from './emojiRegex.js'
|
2018-11-20 00:01:23 -08:00
|
|
|
|
2018-11-25 12:35:52 -08:00
|
|
|
// \ufe0f is a variation selector, which seems to appear for some reason in e.g. ™
|
2019-08-03 13:49:37 -07:00
|
|
|
const NON_EMOJI_REGEX = /^(?:[0-9#*]|™|®|\ufe0f)+$/
|
2018-11-25 12:35:52 -08:00
|
|
|
|
2018-11-20 00:01:23 -08:00
|
|
|
// replace emoji in HTML with something else, safely skipping HTML tags
|
|
|
|
|
export function replaceEmoji (string, replacer) {
|
|
|
|
|
let output = ''
|
|
|
|
|
let leftAngleBracketIdx = string.indexOf('<')
|
|
|
|
|
let currentIdx = 0
|
2019-08-03 13:49:37 -07:00
|
|
|
const emojiRegex = getEmojiRegex()
|
2018-11-20 00:01:23 -08:00
|
|
|
|
|
|
|
|
function safeReplacer (substring) {
|
2018-11-20 09:42:49 -08:00
|
|
|
// emoji regex matches digits and pound sign https://git.io/fpl6J
|
2018-11-25 12:35:52 -08:00
|
|
|
if (substring.match(NON_EMOJI_REGEX)) {
|
2018-11-20 00:01:23 -08:00
|
|
|
return substring
|
|
|
|
|
}
|
|
|
|
|
return replacer(substring)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
while (leftAngleBracketIdx !== -1) {
|
2019-08-03 13:49:37 -07:00
|
|
|
const substring = string.substring(currentIdx, leftAngleBracketIdx)
|
2018-11-20 00:01:23 -08:00
|
|
|
|
|
|
|
|
output += substring.replace(emojiRegex, safeReplacer)
|
|
|
|
|
|
2019-08-03 13:49:37 -07:00
|
|
|
const rightAngleBracketIdx = string.indexOf('>', leftAngleBracketIdx + 1)
|
2018-11-20 00:01:23 -08:00
|
|
|
if (rightAngleBracketIdx === -1) { // broken HTML, abort
|
|
|
|
|
output += string.substring(leftAngleBracketIdx, string.length)
|
|
|
|
|
return output
|
|
|
|
|
}
|
|
|
|
|
output += string.substring(leftAngleBracketIdx, rightAngleBracketIdx) + '>'
|
|
|
|
|
currentIdx = rightAngleBracketIdx + 1
|
|
|
|
|
leftAngleBracketIdx = string.indexOf('<', currentIdx)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
output += string.substring(currentIdx, string.length).replace(emojiRegex, safeReplacer)
|
|
|
|
|
|
|
|
|
|
return output
|
|
|
|
|
}
|