Encoding of strings in JavaScript can either be done in UTF-16 or UTF-8

While browsing through the MDN documentation on charAt, I came across a question about the UTF-16 encoding of strings in JavaScript.

To test my understanding, I decided to run this script in NodeJS:

Buffer.from("€").length // returns 3

I was puzzled by the result showing 3 bytes. Typically, I would expect either 2 or 4 bytes for UTF-16 strings. How is it possible for a UTF-16 string to be 3 bytes long?

Although I searched various questions on StackOverflow, I couldn't find a satisfactory explanation for this particular issue.

Answer №1

When you are creating a Buffer from a string, specifying an encoding is necessary. If none is provided, it will default to UTF-8.

If you are specifically looking for the byte length in UTF-16LE encoding, you can use:

Buffer.from("€", "utf16le").length

Alternatively, you can simply calculate the byte length by multiplying the character length by 2:

"€".length * 2

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

Combine arrays into a single array

If I have an array that contains arrays within it, my goal is to flatten it and create a single array with all the values. let arrWithArrs = [[1,2,3], [4,5,6]]; let array = arrWithArrs.map(arr => ...arr); The current approach does not yield the desire ...

serializeArray() is unable to capture form fields that have been dynamically added to the page after it has finished loading

How come serializeArray() doesn't capture form fields added after page load using #jQuery? What could be the reason behind this limitation and how can it be resolved? Edit: Take a look at the code snippet below. I'm relatively new to javascript/ ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

Experiencing difficulty setting custom maximum value for y-axis on brush chart with ApexCharts

I'm facing an issue with a brushed chart containing two datasets with significantly different values. While I've managed to successfully change the maximum value of the y-axis for both datasets in the brush chart line, the same does not apply to ...

Incorporating dynamic variables into Angular: A beginner's guide

I'm working on a form where user input determines the number of additional input boxes created. Below is the JavaScript code used for this functionality. for(i = 1; i <= c; i++) { //c = total input count block = block + '<div class="ro ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...

jQuery: Choose only one individual div to stay selected

Instructions: Directly underneath the BODY tag, there is a DIV element with the ID of "keepme" that must be retained. All other elements should be removed using the remove() method. Can you accomplish this task using jQuery? Specifically, preserving the s ...

Restricting the size of uploaded files in WebApi

Here is a simple WebApi code snippet that allows for file uploads: [HttpPost] public async Task<bool> UploadSingleFile() { bool isSuccess = false; try { var streamProvider = new MultipartFormDataStreamProvider("D:\\") ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

Searching for a specific string within a file using PHP within the confines of a controller and model

Currently, I am loading a file from a controller and attempting to locate a specific string from that file within a model. The function within the controller that I have created looks like this: <?php public function file() { $filename = " ...

I am attempting to link a child object literal with a parent object literal

In a practical sense, I believe I can provide a clearer description of the problem I am encountering. What I am trying to achieve is linking a child entity to its parent. In my current scenario, I have two models: owner and property. An owner can have mult ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Preventing background scrolling while using a fixed overlay in jQuery/CSS

I'm working on an overlay box that is fixed and centered on the screen. The page it's being used on is pretty lengthy and has a vertical scrollbar. My goal is to prevent scrolling of the main page when the overlay is displayed. However, I can&ap ...

Enter the Angular Date Picker on Safari

While working with Angular and ngx-bootstrap, I encountered an issue where the input type=date does not function properly on Safari Browser. Can anyone suggest a solution to fix this problem? ...

React modal image showing a misaligned image upon clicking

I recently integrated the react-modal-image library into my project to display images in a modal when clicked. However, I encountered an issue where the displayed image is off center with most of it appearing offscreen. I'm unsure what is causing this ...

Mongoose: Discover matching names based on input

Currently, I am developing an auto-complete input box and attempting to create a mongoose endpoint that will retrieve user objects based on the input data. The input data may not be complete, but it should still return similar information. For example: va ...

How can PHP be used to automatically select the current website from a dropdown menu?

I manage several office websites that all feature the same dropdown menu in the page header, allowing visitors to easily navigate between different office locations. While I have already designed the dropdown menu, I am unsure about how to handle the serve ...