Files
housesof/packages/utils/text.ts

25 lines
600 B
TypeScript

/**
* Split text
* @description Split a string into words or characters
* @returns string[]
*/
export const splitText = (text: string, mode = 'words'): string[] => {
// Split by words
if (mode === 'words') {
const words = text
.replace(/\\n/g, '\n')
.replace(/\s+/g, m => m.includes('\n') ? '\n ' : ' ')
.trim()
.split(' ')
return words
}
// Split by chars
else if (mode === 'chars') {
const chars = Array.from(text).map(char => char === ' ' ? '\xa0' : char)
return chars
}
return []
}