JavaScript · Searching and Counting

Searching and Counting

import * as stringzilla from 'stringzilla'; 6.0.0-rc.1 · 91a27bdd

find and findLast locate a needle Buffer inside a haystack Buffer, returning the byte offset as a BigInt, or -1n when absent. An empty needle matches at 0n for find and at the haystack length for findLast.

import assert from "node:assert";

const haystack = Buffer.from("hello world, hello node");
const needle = Buffer.from("hello");

assert.strictEqual(sz.find(haystack, needle), 0n);
assert.strictEqual(sz.findLast(haystack, needle), 13n);

findByte and findLastByte search for a single byte value, a number in 0–255, returning the first or last offset, or -1n.

assert.strictEqual(sz.findByte(haystack, 0x6f), 4n);      // first 'o'
assert.strictEqual(sz.findLastByte(haystack, 0x6f), 19n); // last 'o'

findByteFrom and findLastByteFrom search for the first or last byte that belongs to a set. The set is passed as a Buffer listing the allowed byte values.

const vowels = Buffer.from("aeiou");
assert.strictEqual(sz.findByteFrom(haystack, vowels), 1n);      // first 'e'
assert.strictEqual(sz.findLastByteFrom(haystack, vowels), 22n); // last 'e' in "node"

count returns how many times a needle occurs in a haystack as a BigInt. Pass true as the third argument to count overlapping matches; the default is non-overlapping. An empty needle matches at every offset, the end included, so it counts haystack.length + 1 times.

assert.strictEqual(sz.count(Buffer.from("aaaa"), Buffer.from("aa")), 2n);       // non-overlapping
assert.strictEqual(sz.count(Buffer.from("aaaa"), Buffer.from("aa"), true), 3n); // overlapping

API

Types

FindResultWhere an uncased search matched: the byte index, -1n if not found, and the matched byte length.
stringzilla.d.ts:47 ↗
interface FindResult

Fields

indexbigint
lengthbigint