Total Complexity | 5 |
Complexity/F | 0 |
Lines of Code | 30 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | export const countNumberOfWords = (innerText: string): number => { |
||
2 | if (innerText && innerText.trim()) { |
||
3 | return innerText.replace(/\s+/g, " ").trim().split(" ").length; |
||
4 | } |
||
5 | return 0; |
||
6 | }; |
||
7 | |||
8 | export const stringEndsInWhitespace = (value: string): boolean => { |
||
9 | const pattern = /.*\s$/; // \s represents any whitespace characters, like tabs, spaces and newlines |
||
10 | return pattern.test(value); |
||
11 | }; |
||
12 | |||
13 | export const truncateWords = (value: string, wordLimit: number): string => { |
||
14 | const wordCount = countNumberOfWords(value); |
||
15 | |||
16 | if (wordCount === wordLimit && stringEndsInWhitespace(value)) { |
||
17 | return `${value.trim()} `; |
||
18 | } |
||
19 | |||
20 | if (wordCount > wordLimit) { |
||
21 | // This pattern finds the first n words, where words are characters divided by whitespace, and n=wordLimit |
||
22 | const pattern = new RegExp(`([^\\s]+\\s+){${wordLimit}}`, "g"); |
||
23 | const matches = pattern.exec(value); |
||
24 | if (matches) { |
||
25 | return `${matches[0].trim()} `; |
||
26 | } |
||
27 | } |
||
28 | return value; |
||
29 | }; |
||
30 |