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

2
  • @mbojko that does not provide the information the OP is asking for. Commented Feb 26, 2020 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. Commented Feb 26, 2020 at 13:57

1 Answer 1

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"));

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

4 Comments

This is correct though it's unsupported in Edge and IE11.
You'll need to polyfill for MS browsers.
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 I've updated the solution with a snippet found from stackoverflow.com/a/5015930/2098773

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.