gpt4 book ai didi

Javascript:创建 UTF-16 文本文件?

转载 作者:行者123 更新时间:2023-11-30 07:08:11 24 4
gpt4 key购买 nike

我有一些字符串需要是 UTF-16 文本文件。例如:

var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);

这将产生一个 UTF-8 编码的文本文件。如何获取包含字符串 s 的 UTF-16 文本文件?

最佳答案

相关:Javascript to csv export encoding issue

应该这样做:

document.getElementById('download').addEventListener('click', function(){

downloadUtf16('Hello, World', 'myFile.csv')
});

function downloadUtf16(str, filename) {

// ref: https://stackoverflow.com/q/6226189
var charCode, byteArray = [];

// BE BOM
byteArray.push(254, 255);

// LE BOM
// byteArray.push(255, 254);

for (var i = 0; i < str.length; ++i) {

charCode = str.charCodeAt(i);

// BE Bytes
byteArray.push((charCode & 0xFF00) >>> 8);
byteArray.push(charCode & 0xFF);

// LE Bytes
// byteArray.push(charCode & 0xff);
// byteArray.push(charCode / 256 >>> 0);
}

var blob = new Blob([new Uint8Array(byteArray)], {type:'text/plain;charset=UTF-16BE;'});
var blobUrl = URL.createObjectURL(blob);

// ref: https://stackoverflow.com/a/18197511
var link = document.createElement('a');
link.href = blobUrl;
link.download = filename;

if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
link.dispatchEvent(event);
} else {
link.click();
}
}
<button id="download">Download</button>

关于Javascript:创建 UTF-16 文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937088/

24 4 0
文章推荐: JavaScript setInterval 立即运行
文章推荐: Java事务: how to stop program after rollback?
文章推荐: javascript - 等待来自 CasperJS 中选择的