PluginProbe
Code Snippets / 3.10.0
Code Snippets v3.10.0
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / js / utils / text.ts

text.ts in Code Snippets 3.10.0, at js/utils/text.ts

40 lines 1.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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