forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.ts
More file actions
41 lines (32 loc) · 976 Bytes
/
text.ts
File metadata and controls
41 lines (32 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
export const PUNCTUATION_CHARS = '.!?。.!?'
const SENTENCE_WITH_NEWLINE = new RegExp('[' + PUNCTUATION_CHARS + '\\n]', 'g')
function findLastMatch(
str: string,
pattern: RegExp,
start: number
): string | undefined {
let match
let lastIndex = -1
while ((match = pattern.exec(str)) !== null) {
if (match.index >= start) {
lastIndex = match.index
}
}
if (lastIndex >= 0) {
return str.slice(0, lastIndex + 1)
} else {
return undefined
}
}
export function truncateText(text: string, min: number, max: number): string {
if (text.length <= max) return text
let upToMax = text.slice(0, max)
// Try to cut by sentence
let bySentence = findLastMatch(upToMax, SENTENCE_WITH_NEWLINE, min)
if (bySentence) return bySentence + ' …'
// Try to cut by word
let byWord = findLastMatch(upToMax, /\s/g, min)
if (byWord) return byWord.trimEnd() + ' …'
// Truncate at the middle of the word
return upToMax + '…'
}