Skip to content
Skip to chapter

Chapter 8

JavaScript and the runtime

7 min read

Extract text with regular expressions

Clean copied Workspace text, extract fields with V8 RegExp named capture groups and matchAll, and stamp records with UUIDs and SHA-256 digests.

By the end

Strip invisible Unicode characters from pasted strings, extract validated fields with named capture groups without /g state bugs, and choose between random UUIDs and deterministic SHA-256 digests.

Chapter navigation

Clean raw intake strings copied from emails, chat messages, or documents, extract structured fields with V8 regular expressions (RegExp), collect repeated ticket codes with matchAll(), and stamp each accepted record with both a content-derived SHA-256 hash and a random UUID. You need string and equality rules from Work with JavaScript values and objects, helper functions and loops from Make decisions with functions and loops, and array methods from Work with JavaScript arrays.

Real Workspace text rarely arrives as clean ASCII columns. A line copied out of Gmail, Google Docs, Chat, or a web table often carries non-breaking spaces (\u00A0), zero-width spaces (\u200B), inconsistent letter case, and multiple identifiers inside one sentence. Cleaning invisible characters before running a regular expression keeps string comparisons and pattern matches predictable.

Run the standalone text parser

The example runs in memory with no spreadsheet or Drive setup and requests no OAuth consent.

Code.gs
/**
 * @typedef {{
 *   requestId: string,
 *   department: string,
 *   ownerEmail: string,
 *   title: string,
 *   referencedIds: string[],
 *   contentSha256: string,
 *   recordUuid: string,
 *   summaryLine: string
 * }} ParsedIntakeTextRecord
 */

/**
 * @typedef {{ ok: true, record: ParsedIntakeTextRecord } | { ok: false, rawLine: string, reason: string }} TextParseOutcome
 */

const RAW_INTAKE_TEXT_LINES = [
  '  [REQ-1042]\u00a0dept: Facilities | owner: Avery.Quinn@Example.com | Replace lobby badge reader (blocks REQ-1008 and REQ-1019)  ',
  '[REQ-1043] dept: Finance\u200b | owner: morgan.lee@example.com | Close Q1 travel ledger',
  '[TICKET-99] dept: Legal | owner: sam.chen@example.com | Review vendor addendum',
  '[REQ-1045] dept: HR | owner: jo.patel-at-example.com | Publish onboarding calendar',
];

// Zero-width formatting characters (\u200B..\u200D, \uFEFF) survive String.prototype.trim().
const ZERO_WIDTH_CHARACTERS = /[\u200b-\u200d\ufeff]/g;

// Named capture groups extract each field in one pass after invisible characters and spaces normalize.
const INTAKE_TEXT_PATTERN =
  /^\[(?<requestId>REQ-\d{4})\]\s*dept:\s*(?<department>[A-Za-z][A-Za-z &/-]{0,29})\s*\|\s*owner:\s*(?<ownerToken>\S+)\s*\|\s*(?<title>.+)$/;

const EMAIL_TOKEN_PATTERN = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
const REQUEST_CODE_GLOBAL_PATTERN = /REQ-\d{4}/g;

/**
 * Parses four raw intake lines, strips invisible formatting characters, extracts
 * named regex groups and secondary request mentions, and computes deterministic
 * SHA-256 digests alongside random v4 UUIDs.
 *
 * @returns {void}
 */
function inspectParsedIntakeText() {
  logZeroWidthDemo_();

  /** @type {ParsedIntakeTextRecord[]} */
  const accepted = [];
  /** @type {Array<{ rawLine: string, reason: string }>} */
  const rejected = [];

  for (const rawLine of RAW_INTAKE_TEXT_LINES) {
    const outcome = parseIntakeTextLine(rawLine);
    if (outcome.ok) {
      accepted.push(outcome.record);
    } else {
      rejected.push({ rawLine: outcome.rawLine, reason: outcome.reason });
    }
  }

  Logger.log('Accepted records: ' + accepted.length + '; rejected lines: ' + rejected.length);
  for (const record of accepted) {
    Logger.log(
      record.summaryLine +
        ' | sha256=' +
        record.contentSha256.slice(0, 12) +
        ' | uuid=' +
        record.recordUuid,
    );
  }
  for (const item of rejected) {
    Logger.log('Rejected: ' + item.reason + ' | input="' + cleanInputText(item.rawLine) + '"');
  }
}

/**
 * Shows why String.prototype.trim() removes non-breaking spaces (\u00A0) while
 * leaving zero-width spaces (\u200B) attached to copied text.
 *
 * @returns {void}
 */
function logZeroWidthDemo_() {
  const pastedStatus = 'Active\u200b';
  Logger.log(
    'pastedStatus.trim() === "Active": ' +
      String(pastedStatus.trim() === 'Active') +
      ' (length=' +
      pastedStatus.trim().length +
      ')',
  );
  Logger.log(
    'cleanInputText(pastedStatus) === "Active": ' +
      String(cleanInputText(pastedStatus) === 'Active'),
  );
}

/**
 * Removes zero-width characters, normalizes Unicode composition to NFC, trims
 * outer whitespace (including \u00A0), and collapses interior whitespace runs.
 *
 * @param {string} rawText
 * @returns {string}
 */
function cleanInputText(rawText) {
  if (typeof rawText !== 'string') {
    throw new Error('cleanInputText requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  return rawText
    .normalize('NFC')
    .replace(ZERO_WIDTH_CHARACTERS, '')
    .trim()
    .replace(/\s+/g, ' ');
}

/**
 * Parses one raw intake line into a validated record or an explicit rejection reason.
 *
 * @param {string} rawLine
 * @returns {TextParseOutcome}
 */
function parseIntakeTextLine(rawLine) {
  if (typeof rawLine !== 'string') {
    throw new Error('parseIntakeTextLine requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  const normalized = cleanInputText(rawLine);
  const match = INTAKE_TEXT_PATTERN.exec(normalized);
  if (!match || !match.groups) {
    return {
      ok: false,
      rawLine: rawLine,
      reason: 'Line does not match [REQ-dddd] dept: ... | owner: ... | title',
    };
  }

  const requestId = match.groups.requestId;
  const department = match.groups.department.trim();
  const ownerToken = match.groups.ownerToken;
  const title = match.groups.title.trim();

  if (!EMAIL_TOKEN_PATTERN.test(ownerToken)) {
    return {
      ok: false,
      rawLine: rawLine,
      reason: 'Owner "' + ownerToken + '" is not a valid email token',
    };
  }

  const ownerEmail = ownerToken.toLowerCase();
  const referencedIds = extractReferencedRequestIds(title, requestId);
  const canonicalKey = [requestId, department, ownerEmail, title].join('|');
  const contentSha256 = sha256Hex(canonicalKey);
  const recordUuid = Utilities.getUuid();
  const refsSummary = referencedIds.length > 0 ? referencedIds.join(',') : 'none';
  const summaryLine =
    requestId +
    ' | dept=' +
    department +
    ' | owner=' +
    ownerEmail +
    ' | refs=' +
    refsSummary +
    ' | title="' +
    title +
    '"';

  return {
    ok: true,
    record: {
      requestId: requestId,
      department: department,
      ownerEmail: ownerEmail,
      title: title,
      referencedIds: referencedIds,
      contentSha256: contentSha256,
      recordUuid: recordUuid,
      summaryLine: summaryLine,
    },
  };
}

/**
 * Extracts unique REQ-dddd mentions from free text without mutating a shared lastIndex.
 *
 * @param {string} text
 * @param {string} ownRequestId
 * @returns {string[]}
 */
function extractReferencedRequestIds(text, ownRequestId) {
  if (typeof text !== 'string' || typeof ownRequestId !== 'string') {
    throw new Error(
      'extractReferencedRequestIds requires (text, ownRequestId) string arguments. Select inspectParsedIntakeText to run the sample.',
    );
  }
  /** @type {Set<string>} */
  const uniqueIds = new Set();
  for (const match of text.matchAll(REQUEST_CODE_GLOBAL_PATTERN)) {
    const candidate = match[0];
    if (candidate !== ownRequestId) {
      uniqueIds.add(candidate);
    }
  }
  return Array.from(uniqueIds);
}

/**
 * Computes a lowercase 64-character hexadecimal SHA-256 digest for UTF-8 text.
 * Masks signed Java bytes (-128..127) with 0xff before hexadecimal formatting.
 *
 * @param {string} text
 * @returns {string}
 */
function sha256Hex(text) {
  if (typeof text !== 'string') {
    throw new Error('sha256Hex requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  const signedBytes = Utilities.computeDigest(
    Utilities.DigestAlgorithm.SHA_256,
    text,
    Utilities.Charset.UTF_8,
  );
  return signedBytes.map((byte) => (byte & 0xff).toString(16).padStart(2, '0')).join('');
}

/**
 * Escapes regular expression metacharacters so dynamic text matches literally.
 *
 * @param {string} literalText
 * @returns {string}
 */
function escapeRegExpLiteral(literalText) {
  if (typeof literalText !== 'string') {
    throw new Error('escapeRegExpLiteral requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  return literalText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

Download Code.gs
appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "exceptionLogging": "STACKDRIVER"
}

Download appsscript.json
  1. Open script.google.com and create a standalone project named Intake text and regular expressions.

  2. Replace Code.gs with the complete source above.

  3. Open Project Settings, check Show "appsscript.json" manifest file in editor, return to Editor, replace appsscript.json with the manifest above, and save all files.

  4. Choose inspectParsedIntakeText in the function menu and click Run.

Because Utilities.computeDigest, Utilities.getUuid, RegExp, and Logger.log touch no Workspace files, the script runs immediately without an authorization prompt (see Authorization for Google services).

Open Execution log. Each uuid= value changes on every run while the sha256= prefixes and parsed fields stay identical:

Source
pastedStatus.trim() === "Active": false (length=7)
cleanInputText(pastedStatus) === "Active": true
Accepted records: 2; rejected lines: 2
REQ-1042 | dept=Facilities | owner=avery.quinn@example.com | refs=REQ-1008,REQ-1019 | title="Replace lobby badge reader (blocks REQ-1008 and REQ-1019)" | sha256=3e4b50a3809b | uuid=550e8400-e29b-41d4-a716-446655440000
REQ-1043 | dept=Finance | owner=morgan.lee@example.com | refs=none | title="Close Q1 travel ledger" | sha256=47d3849450b4 | uuid=7c9e6679-7425-40de-944b-e07fc1f90ae7
Rejected: Line does not match [REQ-dddd] dept: ... | owner: ... | title | input="[TICKET-99] dept: Legal | owner: sam.chen@example.com | Review vendor addendum"
Rejected: Owner "jo.patel-at-example.com" is not a valid email token | input="[REQ-1045] dept: HR | owner: jo.patel-at-example.com | Publish onboarding calendar"

Strip invisible characters before matching

Look at the first two lines logged by logZeroWidthDemo_:

Source
pastedStatus.trim() === "Active": false (length=7)
cleanInputText(pastedStatus) === "Active": true

In 'Active\u200b', the seventh character (U+200B, zero-width space) renders with zero pixel width in Google Sheets, Docs, and the Apps Script log. According to MDN's String.prototype.trim() reference, .trim() and the regex whitespace shorthand \s strip Unicode White_Space characters, which includes regular spaces, tabs, newlines, and non-breaking spaces (U+00A0), and excludes Unicode format controls (Cf) such as zero-width space (U+200B), zero-width non-joiner (U+200C), and zero-width joiner (U+200D).

When someone copies a status or department name from a rich-text email or chat client into a Sheet cell, a trailing U+200B survives .trim() and causes status === 'Active' and character-class matches like [A-Za-z &/-] (on REQ-1043's 'Finance\u200b') to fail with two strings that look identical on screen.

cleanInputText(rawText) normalizes four things in a fixed order before any regex runs:

  1. rawText.normalize('NFC') combines decomposed accents (such as 'e' followed by U+0301 from macOS filenames) into canonical single code points ('é') so two spellings of the same name hash and compare equal.

  2. .replace(ZERO_WIDTH_CHARACTERS, '') deletes U+200B through U+200D and stray interior U+FEFF byte-order marks.

  3. .trim() removes leading and trailing spaces, tabs, newlines, and non-breaking spaces (U+00A0).

  4. .replace(/\s+/g, ' ') turns any remaining runs of tabs, newlines, or U+00A0 (such as after [REQ-1042] on line 1) into single ASCII spaces.

tip

Keep cleanInputText for single-line fields such as headers, emails, ticket codes, and statuses. When cleaning multi-line notes where line breaks carry meaning, normalize line endings first with .replace(/\r\n?/g, '\n') and collapse horizontal spaces per line with .replace(/[^\S\n]+/g, ' ') so \n paragraph breaks survive.

Extract named groups with RegExp

Once cleanInputText normalizes the line, parseIntakeTextLine runs INTAKE_TEXT_PATTERN.exec(normalized) using V8 named capturing groups:

Pattern pieceWhat it matchesReason for the constraint
^ and $Start and end of the cleaned stringRejects partial matches buried inside unrelated text.
\[ and \]Literal square bracketsUnescaped [...] starts a character class.
(?<requestId>REQ-\d{4})REQ- plus four digits at match.groups.requestIdRejects non-matching prefixes such as TICKET-99.
(?<department>[A-Za-z][A-Za-z &/-]{0,29})Department starting with an ASCII letter, 1 to 30 charactersLinear-time character class with an explicit length cap, and .trim() removes any space before |.
\s*|\s*Literal pipe delimiter with optional spacesUnescaped | means alternation ("or"), so literal pipes must be escaped as |.
(?<ownerToken>\S+)One non-whitespace tokenCaptures malformed addresses like jo.patel-at-example.com so EMAIL_TOKEN_PATTERN can return an owner-specific error message rather than a generic line-format error.
(?<title>.+)One or more remaining charactersCaptures the rest of the line after the final | delimiter.

Reading match.groups.requestId and match.groups.department documents each field at the call site and keeps working if you later insert an optional group in the middle of the regex. With numbered groups (match[1], match[2]), adding a group shifts every later index by one.

Regex literals versus new RegExp strings

Prefer regex literals (/pattern/flags) for fixed patterns. Passing a string to new RegExp('pattern', 'flags') runs JavaScript's string escape parser before the regex parser sees the characters:

Source
const literalPattern = /^REQ-\d{4}$/; // Matches "REQ-1042"
const brokenConstructor = new RegExp('^REQ-\d{4}$'); // "\d" becomes "d", matching "REQ-dddd"!
const escapedConstructor = new RegExp('^REQ-\\d{4}$'); // Matches "REQ-1042"

Use new RegExp(...) only when assembling a pattern from a runtime string (such as a configurable prefix or placeholder token), and pass that string through escapeRegExpLiteral first so characters like ., +, ?, (, ), [, ], $, or | match literally instead of acting as regex operators.

warning

Avoid nested quantifiers with overlapping character classes such as /^([A-Za-z\s]+)+$/. When a long non-matching line fails at the last character, V8's backtracking regex engine can try exponentially many ways to partition the spaces and letters, stalling your execution toward the 6-minute script limit. Bound token lengths ({0,29}), match delimiters explicitly ([^|]+), and normalize whitespace before matching.

Collect multiple matches without /g state bugs

Notice that INTAKE_TEXT_PATTERN and EMAIL_TOKEN_PATTERN omit the /g (global) flag, while REQUEST_CODE_GLOBAL_PATTERN (/REQ-\d{4}/g) includes /g.

In JavaScript, a RegExp carrying /g or /y mutates its own .lastIndex property each time .test() or .exec() succeeds:

Source
const stateful = /REQ-\d{4}/g;
Logger.log(stateful.test('REQ-1042')); // true  (stateful.lastIndex is now 8)
Logger.log(stateful.test('REQ-1043')); // false! Search started at index 8 of an 8-char string

Keep the two jobs separate:

  • Validating or parsing one string at a time: omit /g so .test() and .exec() always start at index 0.

  • Finding every occurrence inside a string: pass a /g regex to text.matchAll(REQUEST_CODE_GLOBAL_PATTERN). matchAll clones the regular expression internally, yields each full match object (including .index and .groups) in order, and leaves REQUEST_CODE_GLOBAL_PATTERN.lastIndex at 0.

In extractReferencedRequestIds, REQ-1042's title mentions 'blocks REQ-1008 and REQ-1019'. Iterating text.matchAll(REQUEST_CODE_GLOBAL_PATTERN) into a Set deduplicates repeated mentions and skips ownRequestId if the title repeats its own ticket number.

Choose between random UUIDs and SHA-256 content hashes

parseIntakeTextLine attaches two different identifiers to each accepted record because workflows need two different identity guarantees:

HelperOutput on repeat runs with identical inputBest job in an Apps Script workflow
Utilities.getUuid()Different 36-character RFC 4122 v4 UUID every callAssigning a permanent primary key once when a brand-new row or request is first created
Utilities.computeDigest(...)Identical 64-character SHA-256 hex digest whenever the canonical fields matchDetecting duplicate imports, building CacheService lookup keys, and checking whether a row changed since the last export
note

Utilities.computeDigest comes from Apps Script's Java host layer and returns a signed Java byte[] represented in JavaScript as an array of numbers from -128 to 127, not unsigned 0 to 255 values. Calling byte.toString(16) directly on -16 produces '-10' instead of 'f0', corrupting the hexadecimal string. Mask each byte with byte & 0xff ((-16 & 0xff) === 240, (240).toString(16) === 'f0') and pad single-digit values with .padStart(2, '0'), as sha256Hex does in Code.gs. Always pass Utilities.Charset.UTF_8 as the third argument when hashing strings so non-ASCII characters hash identically across accounts.

Common failures

  • status === 'Active' returns false on cells that look identical. Log [...status].map((ch) => ch.codePointAt(0)?.toString(16)) to spot a0 (non-breaking space) or 200b (zero-width space), and pass untrusted text through cleanInputText.

  • new RegExp('^REQ-\d{4}$') rejects 'REQ-1042'. Switch to the regex literal /^REQ-\d{4}$/ or double the backslash inside the string ('^REQ-\\d{4}$').

  • A validation regex rejects every second valid row in a loop. Remove the /g flag from the RegExp passed to .test() or .exec().

  • TypeError: String.prototype.matchAll called with a non-global RegExp argument. matchAll requires the /g flag on its regex argument so it cannot loop forever at index 0.

  • Hex digests contain minus signs or vary in length. Apply (byte & 0xff).toString(16).padStart(2, '0') to every signed byte returned by Utilities.computeDigest.

Exercise: support an optional priority field

Extend INTAKE_TEXT_PATTERN and parseIntakeTextLine so a line may include an optional priority: Low, priority: Medium, or priority: High segment right after dept: ..., defaulting to 'Medium':

  1. Add priority: string to ParsedIntakeTextRecord.

  2. In INTAKE_TEXT_PATTERN, insert (?:\s*\|\s*priority:\s*(?<priority>Low|Medium|High))? immediately after (?<department>[A-Za-z][A-Za-z &/-]{0,29}).

  3. Read const priority = match.groups.priority ?? 'Medium';, include priority in canonicalKey (so changing priority updates contentSha256), and append ' | priority=' + priority to summaryLine.

  4. Add ' | priority: High' after dept: Finance on REQ-1043, run inspectParsedIntakeText, and confirm REQ-1042 logs priority=Medium while REQ-1043 logs priority=High with an updated sha256= prefix.

When finished, delete the disposable standalone project or keep it for reference. Next, read Read and write Sheets in batches to read a sheet table once, update rows in memory, and write the result back in one call.

Project files

Complete source files for this chapter's examples.

Extract structured fields from text with V8 regular expressions and Utilities

Code.gs
/**
 * @typedef {{
 *   requestId: string,
 *   department: string,
 *   ownerEmail: string,
 *   title: string,
 *   referencedIds: string[],
 *   contentSha256: string,
 *   recordUuid: string,
 *   summaryLine: string
 * }} ParsedIntakeTextRecord
 */

/**
 * @typedef {{ ok: true, record: ParsedIntakeTextRecord } | { ok: false, rawLine: string, reason: string }} TextParseOutcome
 */

const RAW_INTAKE_TEXT_LINES = [
  '  [REQ-1042]\u00a0dept: Facilities | owner: Avery.Quinn@Example.com | Replace lobby badge reader (blocks REQ-1008 and REQ-1019)  ',
  '[REQ-1043] dept: Finance\u200b | owner: morgan.lee@example.com | Close Q1 travel ledger',
  '[TICKET-99] dept: Legal | owner: sam.chen@example.com | Review vendor addendum',
  '[REQ-1045] dept: HR | owner: jo.patel-at-example.com | Publish onboarding calendar',
];

// Zero-width formatting characters (\u200B..\u200D, \uFEFF) survive String.prototype.trim().
const ZERO_WIDTH_CHARACTERS = /[\u200b-\u200d\ufeff]/g;

// Named capture groups extract each field in one pass after invisible characters and spaces normalize.
const INTAKE_TEXT_PATTERN =
  /^\[(?<requestId>REQ-\d{4})\]\s*dept:\s*(?<department>[A-Za-z][A-Za-z &/-]{0,29})\s*\|\s*owner:\s*(?<ownerToken>\S+)\s*\|\s*(?<title>.+)$/;

const EMAIL_TOKEN_PATTERN = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
const REQUEST_CODE_GLOBAL_PATTERN = /REQ-\d{4}/g;

/**
 * Parses four raw intake lines, strips invisible formatting characters, extracts
 * named regex groups and secondary request mentions, and computes deterministic
 * SHA-256 digests alongside random v4 UUIDs.
 *
 * @returns {void}
 */
function inspectParsedIntakeText() {
  logZeroWidthDemo_();

  /** @type {ParsedIntakeTextRecord[]} */
  const accepted = [];
  /** @type {Array<{ rawLine: string, reason: string }>} */
  const rejected = [];

  for (const rawLine of RAW_INTAKE_TEXT_LINES) {
    const outcome = parseIntakeTextLine(rawLine);
    if (outcome.ok) {
      accepted.push(outcome.record);
    } else {
      rejected.push({ rawLine: outcome.rawLine, reason: outcome.reason });
    }
  }

  Logger.log('Accepted records: ' + accepted.length + '; rejected lines: ' + rejected.length);
  for (const record of accepted) {
    Logger.log(
      record.summaryLine +
        ' | sha256=' +
        record.contentSha256.slice(0, 12) +
        ' | uuid=' +
        record.recordUuid,
    );
  }
  for (const item of rejected) {
    Logger.log('Rejected: ' + item.reason + ' | input="' + cleanInputText(item.rawLine) + '"');
  }
}

/**
 * Shows why String.prototype.trim() removes non-breaking spaces (\u00A0) while
 * leaving zero-width spaces (\u200B) attached to copied text.
 *
 * @returns {void}
 */
function logZeroWidthDemo_() {
  const pastedStatus = 'Active\u200b';
  Logger.log(
    'pastedStatus.trim() === "Active": ' +
      String(pastedStatus.trim() === 'Active') +
      ' (length=' +
      pastedStatus.trim().length +
      ')',
  );
  Logger.log(
    'cleanInputText(pastedStatus) === "Active": ' +
      String(cleanInputText(pastedStatus) === 'Active'),
  );
}

/**
 * Removes zero-width characters, normalizes Unicode composition to NFC, trims
 * outer whitespace (including \u00A0), and collapses interior whitespace runs.
 *
 * @param {string} rawText
 * @returns {string}
 */
function cleanInputText(rawText) {
  if (typeof rawText !== 'string') {
    throw new Error('cleanInputText requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  return rawText
    .normalize('NFC')
    .replace(ZERO_WIDTH_CHARACTERS, '')
    .trim()
    .replace(/\s+/g, ' ');
}

/**
 * Parses one raw intake line into a validated record or an explicit rejection reason.
 *
 * @param {string} rawLine
 * @returns {TextParseOutcome}
 */
function parseIntakeTextLine(rawLine) {
  if (typeof rawLine !== 'string') {
    throw new Error('parseIntakeTextLine requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  const normalized = cleanInputText(rawLine);
  const match = INTAKE_TEXT_PATTERN.exec(normalized);
  if (!match || !match.groups) {
    return {
      ok: false,
      rawLine: rawLine,
      reason: 'Line does not match [REQ-dddd] dept: ... | owner: ... | title',
    };
  }

  const requestId = match.groups.requestId;
  const department = match.groups.department.trim();
  const ownerToken = match.groups.ownerToken;
  const title = match.groups.title.trim();

  if (!EMAIL_TOKEN_PATTERN.test(ownerToken)) {
    return {
      ok: false,
      rawLine: rawLine,
      reason: 'Owner "' + ownerToken + '" is not a valid email token',
    };
  }

  const ownerEmail = ownerToken.toLowerCase();
  const referencedIds = extractReferencedRequestIds(title, requestId);
  const canonicalKey = [requestId, department, ownerEmail, title].join('|');
  const contentSha256 = sha256Hex(canonicalKey);
  const recordUuid = Utilities.getUuid();
  const refsSummary = referencedIds.length > 0 ? referencedIds.join(',') : 'none';
  const summaryLine =
    requestId +
    ' | dept=' +
    department +
    ' | owner=' +
    ownerEmail +
    ' | refs=' +
    refsSummary +
    ' | title="' +
    title +
    '"';

  return {
    ok: true,
    record: {
      requestId: requestId,
      department: department,
      ownerEmail: ownerEmail,
      title: title,
      referencedIds: referencedIds,
      contentSha256: contentSha256,
      recordUuid: recordUuid,
      summaryLine: summaryLine,
    },
  };
}

/**
 * Extracts unique REQ-dddd mentions from free text without mutating a shared lastIndex.
 *
 * @param {string} text
 * @param {string} ownRequestId
 * @returns {string[]}
 */
function extractReferencedRequestIds(text, ownRequestId) {
  if (typeof text !== 'string' || typeof ownRequestId !== 'string') {
    throw new Error(
      'extractReferencedRequestIds requires (text, ownRequestId) string arguments. Select inspectParsedIntakeText to run the sample.',
    );
  }
  /** @type {Set<string>} */
  const uniqueIds = new Set();
  for (const match of text.matchAll(REQUEST_CODE_GLOBAL_PATTERN)) {
    const candidate = match[0];
    if (candidate !== ownRequestId) {
      uniqueIds.add(candidate);
    }
  }
  return Array.from(uniqueIds);
}

/**
 * Computes a lowercase 64-character hexadecimal SHA-256 digest for UTF-8 text.
 * Masks signed Java bytes (-128..127) with 0xff before hexadecimal formatting.
 *
 * @param {string} text
 * @returns {string}
 */
function sha256Hex(text) {
  if (typeof text !== 'string') {
    throw new Error('sha256Hex requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  const signedBytes = Utilities.computeDigest(
    Utilities.DigestAlgorithm.SHA_256,
    text,
    Utilities.Charset.UTF_8,
  );
  return signedBytes.map((byte) => (byte & 0xff).toString(16).padStart(2, '0')).join('');
}

/**
 * Escapes regular expression metacharacters so dynamic text matches literally.
 *
 * @param {string} literalText
 * @returns {string}
 */
function escapeRegExpLiteral(literalText) {
  if (typeof literalText !== 'string') {
    throw new Error('escapeRegExpLiteral requires a string argument. Select inspectParsedIntakeText to run the sample.');
  }
  return literalText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

appsscript.json

Download file
appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "exceptionLogging": "STACKDRIVER"
}