话不多说,直接上代码。。。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>编码转化</title>
</head>
<body>
</body>
<script>
window.onload = function () {
var text = '这是一段文本, http://www.www.com?a=b&c=文本, <div></div>'
console.log('用来测试转化的原始文本', text)
var utf8Bytes = strToUtf8(text)
console.log('String转UTF-8', utf8Bytes)
var base64Str = utf8ToBase64(utf8Bytes)
console.log('UTF-8转base64', base64Str)
var base64ToUtf8Bytes = base64ToUtf8(base64Str)
console.log('base64转UTF-8字节数组', base64ToUtf8Bytes)
var utf8ToString = utf8ToStr(base64ToUtf8Bytes)
console.log('UTF-8字节数组转为String', utf8ToString)
console.log('转换前后是否相等', text === utf8ToString)
}
// String转为utf-8字节数组
function strToUtf8 (str) {
// URL转码
const code = encodeURIComponent(str)
const bytes = []
for (var i = 0; i < code.length; i++) {
const c = code.charAt(i)
if (c === '%') {
const hex = code.charAt(i + 1) + code.charAt(i + 2)
const hexVal = parseInt(hex, 16)
bytes.push(hexVal)
i += 2
} else bytes.push(c.charCodeAt(0))
}
return bytes
}
// utf-8转为base64编码
function utf8ToBase64 (utf8Bytes) {
// 对字符串进行编码
var encode = encodeURI(utf8Bytes)
// 对编码的字符串转化base64
var base64 = btoa(encode)
return base64
}
// base64编码转为utf-8
function base64ToUtf8 (base64) {
// 对base64转编码
var decode = atob(base64)
// 编码转字符串
var str = decodeURI(decode)
// 字符串转为utf-8字节数组
var utf8Arr = str.split(',')
for (var i = 0; i < utf8Arr.length; i++) {
utf8Arr[i] = utf8Arr[i] - 0
}
return utf8Arr
}
// utf-8字节数组转为String
function utf8ToStr (utf8) {
var encoded = ""
var strtr = ""
for (var i = 0; i < utf8.length; i++) {
encoded += '%' + utf8[i].toString(16)
}
str = decodeURIComponent(encoded)
return str
}
</script>
</html>
结果: