如何将 R 中的转义十六进制数转换为格式为 html 的十六进制数

How can you convert an escaped hexadecimal number in R to a hex number formatted for html

例如: R 有一个转义为“\U0001f923”的表情符号,我想将它传递给一个 html 文件,在该文件中它的格式可用作字符: & # x 1 f 9 2 3 ; ().

如何将 R 中的转义十六进制数转换为 html 格式的十六进制数?

您可以组合函数 utf8ToIntas.hexmode,然后只需将转义字符粘贴到:

as.html <- function(x) paste0("&x", as.hexmode(utf8ToInt(x)), ";")
as.html("\U0001f923")
#> [1] "&x1f923;"

您可以使用它来替换多字节字符,如下所示:

replace_multibytes <- function(x)
{
  as.html <- function(x) paste0("&x", as.hexmode(utf8ToInt(x)), ";")
  char_list <- as.list(unlist(strsplit(x, "")))
  x <- sapply(char_list, function(y) if(length(charToRaw(y)) > 1) as.html(y) else y)
  paste0(x, collapse = "")
}

所以现在你可以做

replace_multibytes("The following need replaced: \U0001f923 \U0001f924")
#> [1] "The following need replaced: &x1f923; &x1f924;"