Skip to content

Commit 8caecf6

Browse files
feat(util): excerpt string
1 parent 15ecaab commit 8caecf6

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

packages/util/index.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ export {
1010
} from "./lib/date.js";
1111
export { sanitise } from "./lib/object.js";
1212
export { ISO_6709_RE } from "./lib/regex.js";
13-
export { md5, randomString, sha1, slugify, supplant } from "./lib/string.js";
13+
export {
14+
excerpt,
15+
md5,
16+
randomString,
17+
sha1,
18+
slugify,
19+
supplant,
20+
} from "./lib/string.js";
1421
export { getCanonicalUrl, isSameOrigin } from "./lib/url.js";
1522
export { isRequired } from "./lib/validation-schema.js";

packages/util/lib/string.js

+30
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,36 @@ import { randomBytes, createHash } from "node:crypto";
22

33
import slugifyString from "@sindresorhus/slugify";
44

5+
/**
6+
* Excerpt a string
7+
* @param {string} string - String to excerpt
8+
* @param {number} value - Maximum number of words
9+
* @param {string} locale - Locale
10+
* @returns {string} Excerpted string
11+
*/
12+
export const excerpt = (string, value = 100, locale = "en") => {
13+
const segmenter = new Intl.Segmenter(locale, { granularity: "word" });
14+
const segments = segmenter.segment(string);
15+
16+
let excerpt = "";
17+
let n = 0;
18+
let words = 0;
19+
[...segments].map((segment) => {
20+
words = segment.isWordLike ? n++ : n;
21+
if (words < value) {
22+
excerpt += segment.segment;
23+
}
24+
25+
return excerpt;
26+
});
27+
28+
if (words > value) {
29+
excerpt += "…";
30+
}
31+
32+
return excerpt;
33+
};
34+
535
/**
636
* Generate MD5 hashed string
737
* @param {string} string - String

packages/util/test/unit/string.js

+6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Buffer } from "node:buffer";
33
import { describe, it } from "node:test";
44

55
import {
6+
excerpt,
67
md5,
78
randomString,
89
sha1,
@@ -11,6 +12,11 @@ import {
1112
} from "../../lib/string.js";
1213

1314
describe("util/lib/string", () => {
15+
it("Excerpts a string", () => {
16+
assert.equal(excerpt("Well, well, well!", 1), "Well…");
17+
assert.equal(excerpt("Well, indeed."), "Well, indeed.");
18+
});
19+
1420
it("Generates MD5 hashed string", () => {
1521
const result = md5("foo");
1622

0 commit comments

Comments
 (0)