JavaScript如何对后台utf8编码的字符串解码?

JavaScript08

JavaScript如何对后台utf8编码的字符串解码?,第1张

JavaScript对utf-8字符可以使用原生的Javascript代码来进行转义后再解码。该编码其实不是utf8,而是unicode编码。这里的字符实际上是html实体。

方法定义如下:

var decodeHtmlEntity = function(str) {

return str.replace(/(\d+)/g, function(match, dec) {

return String.fromCharCode(dec)

})

}

输入:

var str = 'JavaScript高级程序设计'

console.log(decodeHtmlEntity(str))

输出:

JavaScript高级程序设计

java不同编码之间进行转换,都需要使用unicode作为中转。以utf-8转gbk为例,示例代码如下: String t = "这是一个字符串aaa111" String utf8 = new String(t.getBytes( "UTF-8")) System.out.println(utf8) String unicode = new String(utf8.getBytes(),"UTF-8") System.out.println(unicode) String gbk = new String(unicode.getBytes("GBK")) System.out.println(gbk)