words
string
Splits string into an array of its words.
Installation
Import
import { words } from '@tulx/utils';Source Code
Implementation
/**
* Splits string into an array of its words.
*
* @param string - The string to inspect.
* @param pattern - The pattern to match words.
* @returns Returns the words of string.
*
* @example
* ```ts
* words('fred, barney, & pebbles'); // ['fred', 'barney', 'pebbles']
* words('fred, barney, & pebbles', /[^, ]+/g); // ['fred', 'barney', '&', 'pebbles']
* ```
*/
export function words(string: string, pattern?: string | RegExp): string[] {
const defaultPattern = /\p{L}+/gu;
const regex = pattern || defaultPattern;
const matches = string.match(regex);
return matches || [];
}
Example
import { words } from '@tulx/utils';
words('fred, barney, & pebbles'); // ['fred', 'barney', 'pebbles']
words('fred, barney, & pebbles', /[^, ]+/g); // ['fred', 'barney', '&', 'pebbles']Related Functions
camelCase
Converts string to camel case.
capitalize
Converts the first character of string to upper case and the remaining to lower case.
deburr
Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and removing combining diacritical marks.
endsWith
Checks if string ends with the given target string.
escape
Converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.
escapeRegExp
Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in string.