Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance:

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

The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file using the string s?

Answer â„–1

For more information, check out: Dealing with encoding problems when exporting Javascript to csv

Here is the solution that should work:

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

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

function downloadUtf16(str, filename) {

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

// Byte Order Mark for Big Endian
  byteArray.push(254, 255);

// Byte Order Mark for Little Endian
  // byteArray.push(255, 254);

  for (var i = 0; i < str.length; ++i) {
  
    charCode = str.charCodeAt(i);
    
    // Big Endian Bytes
    byteArray.push((charCode & 0xFF00) >>> 8);
    byteArray.push(charCode & 0xFF);
    
    // Little Endian 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);
  
// reference: 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>

Answer â„–2

To convert a JavaScript string into an ArrayBuffer, you can utilize a legacy polyfill for the native TextEncoder API. The TextEncoder documentation specifies support for UTF16 with different endianness. It is likely that libraries offering UTF-16 support in a Text-Encoder-compatible manner will emerge soon, if they haven't already. For instance, let's imagine there's a library with a constructor named ExtendedTextEncoder.

You can then generate a Blob URL to facilitate file downloads for users, bypassing the cumbersome base-64 conversion process.

Here's an example:

s = "aosjdfkzlzkdoaslckjznx"
var encoder = new ExtendedTextEncoder("utf-16be")
var blob = new Blob(encoder.encode(s), "text/plain")
var url = URL.createObjectURL(blob)

From now on, you can utilize url instead of your data: URL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The values returned by a NodeJS script in the Python shell are identical to those returned by Node

The following program was developed to address an issue in another application. In this program, a Python script is called from Node.js to perform a task. The Python script returns results that are then used in Node.js. NodeJS : var pythonShell = require ...

Svelte remains static and is not experiencing re-rendering

I am currently incorporating the history component in Svelte, where it should display when changes occur in the bids array. const bidsArray = [ { player: 0, bidType: 'pass' }, { player: 1, bidType: 'level', level: '1&apos ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

Identifying text within a paragraph using JavaScript regex, excluding any URLs mentioned

How can I use JavaScript on the client side to find a search term in a paragraph while excluding any matches that are part of a URL? I attempted to use the following regex but encountered an error: "A quantifier inside a lookbehind makes it non-fixed widt ...

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...

Looking for a sophisticated approach in Spring MVC to manage the escaping and unescaping of strings being passed to the Front End

Currently, I am in the process of developing a web application utilizing Spring MVC. This project involves retrieving multiple objects from the Database, each containing strings as attributes. It's worth noting that I have no control over the format o ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

Initiate a click action upon receiving a focus event

I can't seem to figure out why this code is not functioning as expected: $('a').focus( function() { $(this).click(); }); Context: I am working on developing a form where navigating through different elements (such as textboxes) will au ...

JQuery enthusiast seeks cheerful clicker for callback upon event binding

Incorporating a complex functionality into a click event is proving to be challenging $(someSelector)).bind('click', someFunction(a,b,c)); function somefunction(a,b,c) { return function() { // dive into complexity $(anotherS ...

Filtering a table based on user selection: specifying column, condition, and value using JavaScript

I am new to JavaScript and looking to implement real-time filtering on a table based on user input. My project utilizes Django and PostgreSQL for storing the table data. template <form action="" method="get" class="inline" ...

The AngularJS error message reads, "The function is not defined as a

Currently, I am working on enhancing my AngularJS application, where I have multiple widgets on a page displaying system status information. My goal is to allow users to hide the heading of a specific widget. There is a 'Settings' button on the ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

Tips for employing numerous if-else conditions utilizing the ternary operator in jsonpath-plus?

JSON { "customer":{ "address":{ "stateRegion":"", "stateRegionCode":"" } } } Code "address.state_code": "$.customer.address.[stateRegion ? state ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "МаР...

Insert a new row into the table using jQuery right above the button

I am working on a table where I need to dynamically add rows in the same rowId upon clicking a specific button. For instance, when the "Add Row 1" button is clicked, a new row should be added under "Some content 1", and so on for other rows. <table i ...

Communicating between iframes and parent elements via events

I'm trying to trigger an event in my iframe using the following code: $('body').trigger('my_event'); However, I want to bind this event on my main page that contains the iframe like this: $('iframe').find('body&ap ...