0

I want to know how to convert a string to UTF-16 in Javascript

I tried charCodeAt() but it only gave me the UTF-16 code of only one character but I want to encode an entire string into UTF-16. I also tried other methods but they have failed. I am using code.org.

1
  • 1
    Strings are UTF-16 encoded by default in JavaScript. Commented May 22, 2024 at 0:10

1 Answer 1

0
function stringToUTF16Array(str) {
    let buffer = new ArrayBuffer(str.length * 2);
    let view = new Uint16Array(buffer);
    for (let i = 0; i < str.length; i++) {
        view[i] = str.charCodeAt(i);
    }
    return view;
}

let str = "test";
let utf16Array = stringToUTF16Array(str);

console.log(utf16Array);

You can use a loop to loop through each character and convert it

Sign up to request clarification or add additional context in comments.

1 Comment

Citation needed on the posted coded, previously posted in this answer which cites a Chrome developers blog as its source. Reaching a reputation of 3000 will gain you the moderator privilege of casting close and open votes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.