| 1 |
import { _x } from '@wordpress/i18n' |
| 2 |
|
| 3 |
const DEFAULT_MAX_CHARS = 150 |
| 4 |
|
| 5 |
export const toCamelCase = (text: string): string => |
| 6 |
text.replace(/-(?<letter>[a-z])/g, (_, letter: string) => letter.toUpperCase()) |
| 7 |
|
| 8 |
export const trimLeadingChar = (text: string, characters: string): string => |
| 9 |
characters.includes(text.charAt(0)) ? text.slice(1) : text |
| 10 |
|
| 11 |
export const trimTrailingChar = (text: string, characters: string): string => |
| 12 |
characters.includes(text.charAt(text.length - 1)) ? text.slice(0, -1) : text |
| 13 |
|
| 14 |
export const truncateChars = (text: string, chars = DEFAULT_MAX_CHARS): string => |
| 15 |
text.length > chars |
| 16 |
? `${text.slice(0, chars)}${_x('…', 'truncated text', 'code-snippets')}` |
| 17 |
: text |
| 18 |
|
| 19 |
export const truncateWords = (text: string, wordCount: number): string => { |
| 20 |
const words = text.trim().split(/\s+/) |
| 21 |
|
| 22 |
return words.length > wordCount |
| 23 |
? `${words.slice(0, wordCount).join(' ')}${_x('…', 'truncated text', 'code-snippets')}` |
| 24 |
: text |
| 25 |
} |
| 26 |
|
| 27 |
export const stripTags = (text: string): string => { |
| 28 |
const document = new DOMParser().parseFromString(text, 'text/html') |
| 29 |
const blockSelector = 'p,div,li,br,h1,h2,h3,h4,h5,h6,tr,td,th,ul,ol,blockquote,table,pre,hr,' + |
| 30 |
'dl,dt,dd,section,article,header,footer,figure,figcaption,' + |
| 31 |
'address,aside,nav,main,fieldset,form,details,summary,dialog,hgroup,caption' |
| 32 |
|
| 33 |
document.body.querySelectorAll('script,style').forEach(element => element.remove()) |
| 34 |
document.body |
| 35 |
.querySelectorAll(blockSelector) |
| 36 |
.forEach(element => element.after(document.createTextNode(' '))) |
| 37 |
|
| 38 |
return (document.body.textContent ?? '').replace(/\s+/g, ' ').trim() |
| 39 |
} |
| 40 |
|