string-extract-class-names examples

Table of Contents

Quick Take

import { strict as assert } from "assert";
import { extract } from "string-extract-class-names";

// extracts classes and/or id's
const str = "div#brambles.nushes#croodles";
const { res, ranges } = extract(str);
assert.deepEqual(res, [
  "#brambles",
  ".nushes",
  "#croodles",
]);
assert.deepEqual(ranges, [
  [3, 12],
  [12, 19],
  [19, 28],
]);

// `res` can be produced by slicing `ranges`:
assert.deepEqual(
  res,
  ranges.map(([from, to]) => str.slice(from, to))
);

Supports legacy bracket notation emails used to use

import { strict as assert } from "assert";
import { extract } from "string-extract-class-names";

// Yahoo has changed many years ago so email template
// must be really arcane to contain this notation
// https://github.com/hteumeuleu/email-bugs/issues/49

assert.deepEqual(extract(`td[id=" abc-def "]`), {
  res: ["#abc-def"],
  ranges: [[8, 15]],
});

// notice the hash # is not covered by range indexes!

Non-parsing algorithm can tackle really dodgy CSS

import { strict as assert } from "assert";
import { extract } from "string-extract-class-names";

// probably invalid input, but works anyway:
assert.deepEqual(
  extract("?#id1#id2? #id3#id4> p > #id5#id6").res,
  ["#id1", "#id2", "#id3", "#id4", "#id5", "#id6"]
);

Processes whole CSS selectors

import { strict as assert } from "assert";
import { extract } from "string-extract-class-names";

assert.deepEqual(
  extract("div.first.second#third a[target=_blank]")
    .res,
  [".first", ".second", "#third"]
);