I'd recommend using Buffer:

Buffer.from('someString', '<input-encoding>').toString('utf-8')

This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

Answer from Lord Elrond on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › TextEncoder › encodeInto
TextEncoder: encodeInto() method - Web APIs | MDN
June 28, 2025 - u8array.subarray(position | 0) : u8array, ); } const u8array = new Uint8Array(8); encodeIntoAtPosition("hello", u8array, 2); console.log(u8array.join()); // 0,0,104,101,108,108,111,0 · To convert a JavaScript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes. The exact UTF-8-to-UTF-16 length ratio for your string depends on the language you are working with:
🌐
Medium
medium.com › @vincentcorbee › utf-16-to-utf-8-in-javascript-18b4b11b6e1e
UTF-16 to UTF-8 in Javascript. How are strings in Javascript encoded… | by Vincentcorbee | Medium
August 5, 2025 - UTF-16 to UTF-8 in Javascript How are strings in Javascript encoded? It might surprise some people that Javascript uses UTF-16 to encode strings. But if your are like me, you might be wondering: how …
🌐
GitHub
gist.github.com › afcc49877d0a5d1ac8cbb3373303c719
Converting to UTF-8 with javascript - Gist - GitHub
Converting to UTF-8 with javascript · Raw · utf8conversion.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
SSOJet
ssojet.com › character-encoding-decoding › utf-8-in-javascript-in-browser
UTF-8 in JavaScript in Browser | Encoding Standards for Programming Languages
JavaScript strings are internally represented using UTF-16. When you need to work with UTF-8 encoded data, such as sending data over a network or saving it to a file, you'll use the TextEncoder and TextDecoder APIs.
🌐
GitHub
gist.github.com › joni › 3760795 › 8f0c1a608b7f0c8b3978db68105c5b1d741d0446
toUTF8Array: Javascript function for encoding a string in UTF8. · GitHub
**UPD:** Here is a similar function inside google closure library: [stringToUtf8ByteArray()](https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143). The fact that strings are UTF16 in the JavaScript's memory has been an opening to me!
🌐
Dirask
dirask.com › snippets › js-convert-string-to-utf8-jo5A4D
❤ 💻 js convert string to utf8 - Dirask
var toUtf8 = function(text) { var surrogate = encodeURIComponent(text); var result = ''; for (var i = 0; i < surrogate.length;) { var character = surrogate[i]; i += 1; if (character == '%') { var hex = surrogate.substring(i, i += 2); if (hex) { result += String.fromCharCode(parseInt(hex, 16)); } } else { result += character; } } return result; }; // Usage example: const utf16Text = 'I ❤️ JS'; // I ❤️ JS const utf8Text = toUtf8(utf16Text); // I ❤️ JS console.log(utf8Text); // I ❤️ JS // See also: // https://dirask.com/questions/What-encoding-uses-JavaScript-to-stores-string-jM73zD
🌐
n8n
community.n8n.io › questions
Convert into utf-8 - Questions - n8n Community
July 3, 2024 - Hello, Coming back to n8n again after short break…!! I wanted to create one function in CODE node… convert string into utf-8 encode. convert string into base64 encode. for this, i used - Buffer.from(str).toStrin…
Find elsewhere
🌐
Burke
kevin.burke.dev › kevin › node-js-string-encoding
Let’s talk about Javascript string encoding | Kevin Burke
September 1, 2017 - Where the cent character is the UTF-8 encoded byte sequence "\xc2\xa2". When Node starts and you try to reference x in your program, it will be re-encoded as a UTF-16 string. If you type the literal characters: ... This will be turned into the UTF-16 string "\xc2\x00\xa2\x00". So be careful to mind your inputs and outputs. Encoding in Node is extremely confusing, and difficult to get right. It helps, though, when you realize that Javascript string types will always be encoded as UTF-16, and most of the other places strings in RAM interact with sockets, files, or byte arrays, the string gets re-encoded as UTF-8.
🌐
npm
npmjs.com › package › utf8
utf8 - npm
December 4, 2017 - Unlike many other JavaScript solutions, it is designed to be a proper UTF-8 encoder/decoder: it can encode/decode any scalar Unicode code point values, as per the Encoding Standard. Here’s an online demo. Feel free to fork if you see possible improvements! ... Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string.
      » npm install utf8
    
Published   Dec 04, 2017
Version   3.0.0
🌐
DEV Community
dev.to › mistval › beware-of-emoji-in-js-144o
JavaScript String Encoding Gotchas - DEV Community
January 21, 2022 - But for fs to do that, it does a conversion from UTF-16 to UTF-8 before writing to the file. Basically, there can be a difference between the encoding used to store strings in memory in JavaScript and the encoding that libraries like fs choose to use by default for I/O.
🌐
npm
npmjs.com › package › string-to-utf8
string-to-utf8 - npm
March 18, 2018 - Encode JavaScript strings in UTF-8. Latest version: 0.1.0, last published: 8 years ago. Start using string-to-utf8 in your project by running `npm i string-to-utf8`. There are no other projects in the npm registry using string-to-utf8.
      » npm install string-to-utf8
    
Published   Mar 18, 2018
Version   0.1.0
Top answer
1 of 2
17

You use the below javascript function to convert unicode to utf-8

function encode_utf8( s ){
    return unescape( encodeURIComponent( s ) );
}( '\u4e0a\u6d77' )

You can also try it out in firebug console. It works.

2 of 2
2
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>UTF-8 To Unicode</title>
    <style type="text/css">
    <!--
    td {
        height: 24px;
        line-height: 24px;
    }
    #content {
        margin-top: 2px;
    }
    -->
    </style>
    </head>
    <script type="text/javascript">
        function encodeGB2312(){
            var c = document.all.content.value;
            var re = /(%)+/g;
            var result =  escape(c);
            document.all.content.value =  result.replace(re, "\\");
            document.all.content.focus();
            document.all.content.select();
        }
        function clearContent(){
            document.all.content.value = "";
            document.all.content.focus();
        }
    </script>

    <body>
        <h3 align="center">UTF-8 To Unicode</h3>
        <table width="600" border="1" cellspacing="0" cellpadding="0" align="center"         style="text-align:center;">
          <tr>
            <td>Input what you want to convert:</td>
            <td><input type="text" name="content" id="content" size="50"/></td>
          </tr>
          <tr>
            <td colspan="2">
            <input type="button" name="encoding" value="Start Conversion"         onclick="encodeGB2312()"/>&nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" name="clear" value=" Cancel" onclick="clearContent();"/></td>
          </tr>
        </table>
    </body>
    </html>

This is a sample of convert utf-8 to unicode, do it in turn.

🌐
GitHub
github.com › mathiasbynens › utf8.js
GitHub - mathiasbynens/utf8.js: A robust JavaScript implementation of a UTF-8 encoder/decoder, as defined by the Encoding Standard. · GitHub
Unlike many other JavaScript solutions, it is designed to be a proper UTF-8 encoder/decoder: it can encode/decode any scalar Unicode code point values, as per the Encoding Standard. Here’s an online demo. Feel free to fork if you see possible improvements! ... Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string.
Author   mathiasbynens
🌐
MojoAuth
mojoauth.com › character-encoding-decoding › utf-8-encoding--javascript-in-browser
UTF-8 Encoding : JavaScript in Browser | Encoding Solutions Across Programming Languages
Encoding text in UTF-8 format in JavaScript can be done using the TextEncoder API, which is supported in most modern browsers. The TextEncoder class allows you to convert strings into a sequence of bytes encoded in UTF-8.
Top answer
1 of 3
2

What you want to do is encode your string as UTF8. Googling for how to do that in Javascript, I found http://monsur.hossa.in/2012/07/20/utf-8-in-javascript.html , which gives:

function encode_utf8( s ) {
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s ) {
  return decodeURIComponent( escape( s ) );
}

or in short, almost exactly what you found already, plus unescaping the '%xx' codes to a byte.

2 of 3
1

You can get the ASCII value of a character with .charCodeAt(position). You can split a character into multiple characters using this.

First, get the char code for every character, by looping trough the string. Create a temporary empty string, and while the char code is higher than 255 of the current character, divide 255 from it, and put a ÿ (the 256th character of the extended ASCII table), then once it's under 255 use String.fromCharCode(charCode), to convert it to a character, and put it at the end of the temporary string, and at last, replace the character with this string.

function encode(string) {
    var result = [];
    for (var i = 0; i < string.length; i++) {
    var charCode = string.charCodeAt(i);
        var temp = "";
        while (charCode > 255) {
            temp += "ÿ";
            charCode -= 255;
        }
        result.push(temp + String.fromCharCode(charCode));
    }
    return result.join(",");
}

The above encoder puts a comma after every group, this could cause problems at decode, so we need to use the ,(?!,) regex to match the last comma from multiple commas.

function decode(string) {
    var characters = string.split(/,(?!,)/g);
    var result = "";
    for (var i = 0; i < characters.length; i++) {
        var charCode = 0;
        for (var j = 0; j < characters[i].length; j++) {
            charCode += characters[i].charCodeAt(j);
        }
        result += String.fromCharCode(charCode);
    }
    return result;
}