如何将R中的转义十六进制数转换为格式化为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;"

最新更新