Split Binary Data with Search Data using Google Apps Script

Gists

This is a sample script for splitting the binary data with search data using Google Apps Script.

Sample script

/**
 * Split byteArray by a search data.
 * @param {Array} baseData Input byteArray of base data.
 * @param {Array} searchData Input byteArray of search data using split.
 * @return {Array} An array including byteArray.
 */
function splitByteArrayBySearchData_(baseData, searchData) {
  if (!Array.isArray(baseData) || !Array.isArray(searchData)) {
    throw new Error("Please give byte array.");
  }
  const search = searchData.join("");
  const bLen = searchData.length;
  const res = [];
  let idx = 0;
  do {
    idx = baseData.findIndex(
      (_, i, a) => [...Array(bLen)].map((_, j) => a[j + i]).join("") == search
    );
    if (idx != -1) {
      res.push(baseData.splice(0, idx));
      baseData.splice(0, bLen);
    } else {
      res.push(baseData.splice(0));
    }
  } while (idx != -1);
  return res;
}

// Please run this function.
function main() {
  const sampleString = "abc123def123ghi123jkl";
  const splitValue = "123";

  const res1 = splitByteArrayBySearchData(
    ...[sampleString, splitValue].map((e) => Utilities.newBlob(e).getBytes())
  );
  const res2 = res1.map((e) => Utilities.newBlob(e).getDataAsString());

  console.log(res1); // [[97,98,99],[100,101,102],[103,104,105],[106,107,108]]
  console.log(res2); // ["abc","def","ghi","jkl"]
}
  • When main() is run, the sample input values of "abc123def123ghi123jkl" is split by "123". And, [[97,98,99],[100,101,102],[103,104,105],[106,107,108]] is obtained. In this case, when [[97,98,99],[100,101,102],[103,104,105],[106,107,108]] is converted to the string for confirming the result value, it becomes ["abc","def","ghi","jkl"].

  • In this case, of course, the method of splitByteArrayBySearchData_ uses the binary data (in this case, it’s a byte array.). As another sample script, you can see this thread on Stackoverflow .

 Share!