Installation
Quick Take
Examples
- Supports legacy bracket notation emails used to use
- Non-parsing algorithm can tackle really dodgy CSS
- Processes whole CSS selectors
API — extract()
The main function extract()
is imported like this:
It’s a function which takes one input argument:
Input argument | Type | Obligatory | Description |
---|---|---|---|
str Type: String Obligatory: yes | |||
str | String | yes | A string to process |
The function will return a plain object (a Result
type above):
Key in a returned object | Type | Description |
---|---|---|
res Type: Array of strings | ||
res | Array of strings | Array of extracted classes/id’s |
ranges Type: Array of one or more arrays or null (compatible with Ranges libraries) | ||
ranges | Array of one or more arrays or null (compatible with Ranges libraries) | Locations of extracted strings |
API — version
You can import version
:
The Use
We use string-extract-class-names
to extract all the CSS class and id names from HTML/CSS in the library email-comb which detects and deletes the unused CSS styles.
Bracket notation
Normally, classes or id’s in css include dots/hashes, for example, div.first-class.second-class
. Those dots and hashes end up covered by indexes under ranges
key:
import { extract } from "string-extract-class-names";
const res = extract("div.first-class.second-class");
console.log(res);
// => {
// res: [".first-class", ".second-class"],
// ranges: [
// [3, 15],
// [15, 28],
// ],
// }
Dots above are at indexes 3
and 15
.
However, this program also supports the bracket notation — instead of td.croodles
one can say td[class="croodles"]
. It used to be the way how email templates were setting CSS because of Yahoo. Not any more, but this program still supports bracket notation:
import { extract } from "string-extract-class-names";
const str = `td[id=" abc-def "]`;
const res = extract(str);
console.log(res);
// => {
// res: ["#abc-def"],
// ranges: [[8, 15]],
// }
// however
console.log(str.slice(8, 15));
// => "abc-def"
// notice there's no hash if you slice the source
// because it didn't exist at the first place
In “normal” CSS where dots and hashes do exist, the res
output will match what could be mapped against String.prototype.slice()
(as seen in examples):
assert.deepEqual(
res,
ranges.map(([from, to]) => str.slice(from, to))
);