How do you truncate a String to a max number of bytes in Google Apps Script?

Viewed 31

I am parsing a JSON object obtained by URLFetchApp.fetch() and need to truncate a string value to a max number of bytes. It seems like some combination of the Google Apps Script Utilities Class and HTTPResponse Class is where I will find the answer, but I can not figure out which methods to use and how to put them together.

{object: {key: 'string'}}

something like:

object.key.string.toBytes().substringAsBytes(0,maxBytes).backToString()

https://developers.google.com/apps-script/reference/utilities

https://developers.google.com/apps-script/reference/url-fetch/http-response

1 Answers

Use with Array.splice:

const str = { obj: { key: 'string' } }.obj.key,
  maxBytes = 10,
  byteData = Utilities.newBlob(str).getBytes();
byteData.splice(maxBytes);
const truncatedStr = Utilities.newBlob(byteData).getDataAsString();
Related