2022年10月18日 星期二

文字轉成「字元值參照」

即是把文字轉成 &#xxxx;的格式,例如「你好」轉為「你好」。

各種語言的轉換法

Go

Go 算是我所知的語言中,最簡單的了。因為這已經是內建的語法了

Go 每個文字都能轉成一個 rune ,而 rune 本身就是 int32,所以可以用以下方式來處理

s := "你好"
for _, r := range []rune(s) {
	fmt.Printf("&#%d;", r)
}
Javascript / Typescript

我以前有寫過一個 JS library 可以處理:Numeric-Character-Reference-js

用此 library 的話:

let s = "你好"
console.log(NCR.decode(s))
Java

Apache 有出一個 library 可以用以處理:Apache Commons Text

其 Maven repository 為:https://mvnrepository.com/artifact/org.apache.commons/commons-text

利用其內的 org.apache.commons.text.StringEscapeUtils 和 org.apache.commons.text.translate.NumericEntityEscaper 就可以處理:

String s = "你好";
System.out.println(
	StringEscapeUtils.builder(new NumericEntityEscaper()).escape(s)
);

因為 NumericEntityEscaper 默認會將所有字元,即便是 ASCII 所包含的 'A''0'等等,全都轉換。如果只要轉換 ASCII 以外的,可以改成:

String s = "你好";
System.out.println(
	StringEscapeUtils.builder(NumericEntityEscaper.above(0x00ff)).escape(s)
);

專有名詞說明

沒有留言:

張貼留言