Skip to content

JavaScript Utilities Library

Small, tested functions to paste into your scripts: string cleanup, amounts, dates, arrays, safe metadata reads and simple validation. Each one is plain ES5, uses no host objects, and avoids features that differ between the KnowledgeLake engines. Copy only the functions you need.

At a glance

  • Works in Every JavaScript surface: Custom Behaviors, search filter behaviors, Custom Step, Custom Event, routes, JavaScript step settings, Intuitive AI scripts and Custom Gizmos.
  • Style var and plain functions, no Intl, no timers, no host objects.
  • Dates Whole days in UTC, the way date fields store them.
  • With an assistant Paste the functions you want together with the surface block, and ask the assistant to use them instead of writing its own.

Functions on this page

Function Use it to Group
padLeft, padRight Pad a value to a fixed length Strings
truncate Shorten a value and mark the cut Strings
toTitleCase Capitalize each word Strings
normalizeKey Prepare a value for a lookup or comparison Strings
digitsOnly, removeSpecialChars Strip characters Strings
parseAmount Turn an amount into a number Numbers
formatAmount Format a number with separators Numbers
roundTo Round to a number of decimals Numbers
parseDateUtc Read a date as midnight UTC Dates
formatDateUtc Write a date in a fixed format Dates
addDaysUtc, addBusinessDaysUtc, daysBetweenUtc Date arithmetic Dates
unique, sum, findWhere, groupBy Work with lists Arrays
getPath Read a nested value with a default Objects and metadata
toEventValue Make a Custom Event property value Objects and metadata
isNotEmpty, isValidEmail, isValidUSPhone Simple validation Validation

Engines and surfaces

Surface Engine
Custom Behavior QuickJS in the browser. V8 on the server (Run Indexing Behaviors, Start QC Task, Search bulk edit).
Search filter behavior QuickJS in the browser
Custom Step, Custom Event step V8
Workflow route, JavaScript step setting V8
Intuitive AI conditions and actions V8
Custom Gizmo The user's browser

What to avoid in shared helpers

  • Intl and locale formatting. QuickJS has no Intl, and toLocaleString does not add separators there. Format numbers by hand (see formatAmount).
  • Local-time date methods on stored dates. Date fields are ISO 8601 strings in UTC. Use the getUTC... methods.
  • console, fetch, require, timers. None exist in behaviors, Custom Step, Custom Event, routes or Intuitive AI scripts.

Where to paste a helper

  • Behavior, Custom Step, Custom Event Paste the functions at the top of the script.
  • Intuitive AI script Paste them inside the (function () { ... })(); wrapper.
  • Route or JavaScript step setting The last value of the code decides the result. Wrap the helper and the expression in a function that you call at once:
A helper inside a JavaScript route
(function () {
    function parseAmount(value) {
        var n = parseFloat(String(value || "").replace(/[^0-9.\-]/g, ""));
        return isNaN(n) ? 0 : n;
    }
    var index = workItem.Metadata["Index"] || {};
    return parseAmount(index["InvoiceTotal"]) > parseAmount(GlobalVariables.Get("ReviewLimit"));
})()

Strings

padLeft, padRight

Pads a value to a fixed length, for example an invoice sequence number.

padLeft and padRight
function padLeft(str, length, ch) {
    str = String(str);
    ch = ch || "0";
    while (str.length < length) { str = ch + str; }
    return str;
}

function padRight(str, length, ch) {
    str = String(str);
    ch = ch || " ";
    while (str.length < length) { str = str + ch; }
    return str;
}

// padLeft("42", 5)          -> "00042"
// padRight("Hello", 8, ".") -> "Hello..."

truncate

Shortens a value for a field with a length limit, and marks the cut.

truncate
function truncate(str, maxLength) {
    str = String(str || "");
    if (str.length <= maxLength) { return str; }
    return str.substring(0, maxLength - 3) + "...";
}

// truncate("This is a long string", 15) -> "This is a lo..."

toTitleCase

Capitalizes each word. Names such as McDonald need manual handling.

toTitleCase
function toTitleCase(str) {
    return String(str || "").toLowerCase().replace(/(^|[\s'-])([a-z])/g, function (m, before, letter) {
        return before + letter.toUpperCase();
    });
}

// toTitleCase("mary o'brien-smith") -> "Mary O'Brien-Smith"

normalizeKey

Trims, collapses inner spaces and uppercases, for values used in lookups and comparisons. SQL lookups are case-sensitive, so normalize before a lookup runs.

normalizeKey
function normalizeKey(str) {
    return String(str || "").replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "").toUpperCase();
}

// normalizeKey("  ab   1001 ") -> "AB 1001"

digitsOnly, removeSpecialChars

digitsOnly and removeSpecialChars
function digitsOnly(str) {
    return String(str || "").replace(/\D/g, "");
}

function removeSpecialChars(str) {
    return String(str || "").replace(/[^a-zA-Z0-9\s]/g, "");
}

// digitsOnly("Phone: (555) 123-4567")      -> "5551234567"
// removeSpecialChars("Hello! @World#123")  -> "Hello World123"

Numbers

parseAmount

Converts a stored or typed amount to a number. Returns 0 for empty or unreadable text. Set decimalComma to true for values such as 1.234,56.

parseAmount
function parseAmount(value, decimalComma) {
    var s = String(value === undefined || value === null ? "" : value);
    if (decimalComma) {
        s = s.replace(/\./g, "").replace(/,/g, ".");
    } else {
        s = s.replace(/,/g, "");
    }
    s = s.replace(/[^0-9.\-]/g, "");
    var n = parseFloat(s);
    return isNaN(n) ? 0 : n;
}

// parseAmount("$1,234.56")       -> 1234.56
// parseAmount("1.234,56", true)  -> 1234.56
// parseAmount("")                -> 0

formatAmount

Fixed decimals and thousands separators, without Intl. Write the result only to a Textbox field, never to a Currency or NumericUpDown field.

formatAmount
function formatAmount(num, decimals, symbol) {
    decimals = decimals === undefined ? 2 : decimals;
    var n = Number(num);
    if (isNaN(n)) { n = 0; }
    var negative = n < 0;
    var parts = Math.abs(n).toFixed(decimals).split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return (negative ? "-" : "") + (symbol || "") + parts.join(".");
}

// formatAmount(1234.5)             -> "1,234.50"
// formatAmount(-98765.432, 2, "$") -> "-$98,765.43"

roundTo

Returns a number. Use toFixed when you need a string with trailing zeros, for example before a metadata write.

roundTo
function roundTo(num, decimals) {
    var factor = Math.pow(10, decimals);
    return Math.round(Number(num) * factor) / factor;
}

// roundTo(3.14159, 2) -> 3.14
// roundTo(10.999, 1)  -> 11

Dates

These helpers work in whole days in UTC, which matches how date fields store values.

parseDateUtc

Reads YYYY-MM-DD, a full ISO string or MM/DD/YYYY, and returns a Date at midnight UTC, or null. It parses MM/DD/YYYY itself, because engines differ on that format.

parseDateUtc
function parseDateUtc(value) {
    var s = String(value || "").replace(/^\s+|\s+$/g, "");
    var m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s);
    if (m) { return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])); }
    m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(s);
    if (m) { return new Date(Date.UTC(+m[3], +m[1] - 1, +m[2])); }
    return null;
}

// parseDateUtc("2026-10-07T00:00:00.000Z") -> 2026-10-07 (UTC)
// parseDateUtc("10/07/2026")               -> 2026-10-07 (UTC)
// parseDateUtc("next week")                -> null

formatDateUtc

Pass a Date. Formats: YYYY-MM-DD, MM/DD/YYYY, DD/MM/YYYY.

formatDateUtc
function formatDateUtc(date, format) {
    if (!date || isNaN(date.getTime())) { return ""; }
    var y = String(date.getUTCFullYear());
    var mo = (date.getUTCMonth() + 1 < 10 ? "0" : "") + (date.getUTCMonth() + 1);
    var d = (date.getUTCDate() < 10 ? "0" : "") + date.getUTCDate();
    if (format === "MM/DD/YYYY") { return mo + "/" + d + "/" + y; }
    if (format === "DD/MM/YYYY") { return d + "/" + mo + "/" + y; }
    return y + "-" + mo + "-" + d;
}

// formatDateUtc(new Date(Date.UTC(2026, 9, 7)), "MM/DD/YYYY") -> "10/07/2026"

To write a date into a date field from a behavior, use date.toISOString(), not a formatted string.

addDaysUtc, addBusinessDaysUtc, daysBetweenUtc

Pass Date values from parseDateUtc.

addDaysUtc, addBusinessDaysUtc and daysBetweenUtc
function addDaysUtc(date, days) {
    return new Date(date.getTime() + days * 86400000);
}

function addBusinessDaysUtc(date, days) {
    var result = new Date(date.getTime());
    var added = 0;
    while (added < days) {
        result = new Date(result.getTime() + 86400000);
        var dow = result.getUTCDay();
        if (dow !== 0 && dow !== 6) { added++; }
    }
    return result;
}

function daysBetweenUtc(date1, date2) {
    return Math.round((date2.getTime() - date1.getTime()) / 86400000);
}

// daysBetweenUtc(parseDateUtc("2026-01-01"), parseDateUtc("2026-01-31")) -> 30

addBusinessDaysUtc loops once per day. Keep days small in behaviors, which have a 5 second limit (1.5 seconds in search).

Arrays

unique, sum, findWhere, groupBy

unique, sum, findWhere and groupBy
function unique(arr) {
    var seen = {};
    var out = [];
    for (var i = 0; i < arr.length; i++) {
        var k = String(arr[i]);
        if (!seen.hasOwnProperty(k)) { seen[k] = true; out.push(arr[i]); }
    }
    return out;
}

function sum(arr, key) {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        var v = key ? arr[i][key] : arr[i];
        var n = parseFloat(v);
        total += isNaN(n) ? 0 : n;
    }
    return total;
}

function findWhere(arr, key, value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i][key] === value) { return arr[i]; }
    }
    return null;
}

function groupBy(arr, key) {
    var result = {};
    for (var i = 0; i < arr.length; i++) {
        var g = typeof key === "function" ? key(arr[i]) : arr[i][key];
        if (!result[g]) { result[g] = []; }
        result[g].push(arr[i]);
    }
    return result;
}

// unique(["A", "B", "A"])                               -> ["A", "B"]
// sum([{ amount: "10" }, { amount: "20.5" }], "amount") -> 30.5

In Intuitive AI scripts, host collections are .NET objects, not JavaScript arrays. Copy them into an array before you pass them to these helpers.

Objects and metadata

getPath

Reads a nested value and returns a default when any level is missing. Use it for work item metadata, where a missing bucket is undefined.

getPath
function getPath(obj, path, defaultValue) {
    var keys = path.split(".");
    var cur = obj;
    for (var i = 0; i < keys.length; i++) {
        if (cur === null || cur === undefined) { return defaultValue; }
        cur = cur[keys[i]];
    }
    return cur === undefined || cur === null ? defaultValue : cur;
}

// In a Custom Step or Custom Event:
// var vendor = getPath(batch, "Metadata.Index.Vendor", "");

Keys that contain a dot or a space need bracket access instead: (batch.Metadata["Index"] || {})["Invoice Total"].

toEventValue

Turns any value into a string that a Custom Event property accepts. A Custom Event step fails on an object or array value, and a number or boolean is converted in .NET style (True, not true).

toEventValue
function toEventValue(value) {
    if (value === null || value === undefined) { return ""; }
    if (typeof value === "object") { return JSON.stringify(value); }
    return String(value);
}

// builder.SetEventProperty("documentCount", toEventValue(batch.Documents.length));
// toEventValue({ a: 1 }) -> "{\"a\":1}"
// toEventValue(true)     -> "true"

Validation

isNotEmpty, isValidEmail, isValidUSPhone

isNotEmpty, isValidEmail and isValidUSPhone
function isNotEmpty(value) {
    return value !== null && value !== undefined && String(value).replace(/\s/g, "") !== "";
}

function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email || ""));
}

function isValidUSPhone(phone) {
    return String(phone || "").replace(/\D/g, "").length === 10;
}

// isNotEmpty("   ")                 -> false
// isValidEmail("user@example.com")  -> true
// isValidUSPhone("(555) 123-4567")  -> true