add split string to array function

This commit is contained in:
Jesper Møller Jensen
2023-12-08 13:10:04 +13:00
committed by Jacob Overgaard
parent 5b3e56afa4
commit 33b7891c1b
2 changed files with 25 additions and 0 deletions

View File

@@ -11,6 +11,7 @@ export * from './path-folder-name.function.js';
export * from './selection-manager.js';
export * from './udi-service.js';
export * from './umbraco-path.function.js';
export * from './split-string-to-array.js';
declare global {
interface Window {

View File

@@ -0,0 +1,24 @@
/**
* Splits a string into an array using a specified delimiter,
* trims whitespace from each element, and removes empty elements.
*
* @param {string} string - The input string to be split and processed.
* @param {string} [split=','] - The delimiter used for splitting the string (default is comma).
* @returns {string[]} An array of non-empty, trimmed strings.
*
* @example
* const result = splitStringToArray('one, two, three, ,five');
* // result: ['one', 'two', 'three', 'five']
*
* @example
* const customDelimiterResult = splitStringToArray('apple | orange | banana', ' | ');
* // customDelimiterResult: ['apple', 'orange', 'banana']
*/
export function splitStringToArray(string: string, split = ',') {
return (
string
.split(split)
.map((s) => s.trim())
.filter((s) => s.length > 0) ?? []
);
}