1

I use this C# code to find out how many bytes my string has:

private void CalculateBytes(string text)
{
    string s = Convert.ToString(text);
    int len = Encoding.UTF8.GetByteCount(s);
}

But I don't know how to do the same thing in javascript. How can I calculate the bytes of my string in javascript?

UPDATE:

TextEncoder() and Buffer are not working. I get an error message:

"Error": { "Error": "JavascriptException", "Message": "JavascriptException", "StackTrace": "ReferenceError: Buffer is not defined\n at getBinarySize (BFD0A-main.js:763:5)\n at handlers.GetBytesFromText (BFD0A-main.js:756:24)\n at Object.invokeFunction (Script:116:33)" }

var text = "Text"; 
var bytes = (new TextEncoder().encode(text)).length;

Buffer.byteLength(text, 'utf8'))

I use Microsoft PlayFab Cloud Script: https://learn.microsoft.com/en-us/gaming/playfab/features/automation/cloudscript/quickstart

Tobey60
  • 147
  • 1
  • 5
  • @mbojko that does not provide the information the OP is asking for. – Pointy Feb 26 '20 at 13:54
  • To do this, it would be necessary to construct a list of the UTF-8 code sequences from the UTF-16 sequence in the string, explicitly detecting surrogate UTF-16 pairs along the way. – Pointy Feb 26 '20 at 13:57

1 Answers1

3

You could use the TextEncoder.Encode function and then get the length of that.

var text = "Text"; 
var bytes = (new TextEncoder().encode(text)).length;
document.write("Number of bytes: " + bytes);

As pointing out in the comments you'll need a polyfill for this to work in IE11 or Edge.

Update: Alternative solution found from https://stackoverflow.com/a/5015930/2098773

function getUTF8Length(string) {
    var utf8length = 0;
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
            utf8length++;
        }
        else if((c > 127) && (c < 2048)) {
            utf8length = utf8length+2;
        }
        else {
            utf8length = utf8length+3;
        }
    }
    return utf8length;
 }
 
 document.write(getUTF8Length("Test"));
ZarX
  • 1,096
  • 9
  • 17
  • This is correct though it's unsupported in Edge and IE11. – Pointy Feb 26 '20 at 14:00
  • You'll need to [polyfill](https://www.npmjs.com/package/text-encoding-polyfill) for MS browsers. – spender Feb 26 '20 at 14:00
  • It's not working. I get this error message: "Error": { "Error": "JavascriptException", "Message": "JavascriptException", "StackTrace": "ReferenceError: TextEncoder is not defined\n at GetStringBytes (BFD0A-main.js:769:17)\n at handlers.GetBytesFromText (BFD0A-main.js:755:26)\n at Object.invokeFunction (Script:116:33)" } – Tobey60 Feb 26 '20 at 14:58
  • @Tobey60 I've updated the solution with a snippet found from https://stackoverflow.com/a/5015930/2098773 – ZarX Feb 26 '20 at 15:39