I'm trying to use TextEncoder in Apps Script:
const textEncoder = new TextEncoder("utf-8");
let str = "test";
alert(textEncoder.encode(str));
But I'm getting this error: ReferenceError: TextEncoder is not defined
I guess it's not supported by Apps Script. Is there a way to use TextEncoder in Apps Script (maybe I'm missing a reference), or a 'long way' of doing the code above using other JS or Apps Script commands?
Thanks in advance!
CodePudding user response:
I believe your goal is as follows.
You want to convert the following Javascript to Google Apps Script.
const textEncoder = new TextEncoder("utf-8"); let str = "test"; alert(textEncoder.encode(str));
- When this script is run,
116,101,115,116
is returned.
- When this script is run,
Unfortunately, at Google Apps Script, new TextEncoder
cannot be used. So, in this case, how about the following sample script?
Sample script:
function myFunction() {
const str = "test";
const res = Utilities.newBlob(str).getBytes();
console.log(res) // [ 116, 101, 115, 116 ]
}
At Google Apps Script, UTF-8 is used as the default.
When this script is run, you can see the value of
[ 116, 101, 115, 116 ]
at the log.In the case of
const res = Utilities.newBlob(str).getBytes()
, the array of twos-complement 8-bit signed integers is returned. This is for Google Apps Script.If you want to retrieve the array of 8-bit unsigned integers, please modify as follows.
From
const res = Utilities.newBlob(str).getBytes();
To
const res = [...Uint8Array.from(Utilities.newBlob(str).getBytes())];