From 33b7891c1b4338e2e412aa5512057e4724b6e9c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesper=20M=C3=B8ller=20Jensen?= <26099018+JesmoDev@users.noreply.github.com> Date: Fri, 8 Dec 2023 13:10:04 +1300 Subject: [PATCH] add split string to array function --- .../src/shared/utils/index.ts | 1 + .../src/shared/utils/split-string-to-array.ts | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/Umbraco.Web.UI.Client/src/shared/utils/split-string-to-array.ts diff --git a/src/Umbraco.Web.UI.Client/src/shared/utils/index.ts b/src/Umbraco.Web.UI.Client/src/shared/utils/index.ts index 7b605bb5de..966c6dbabc 100644 --- a/src/Umbraco.Web.UI.Client/src/shared/utils/index.ts +++ b/src/Umbraco.Web.UI.Client/src/shared/utils/index.ts @@ -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 { diff --git a/src/Umbraco.Web.UI.Client/src/shared/utils/split-string-to-array.ts b/src/Umbraco.Web.UI.Client/src/shared/utils/split-string-to-array.ts new file mode 100644 index 0000000000..267c3c4b4e --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/shared/utils/split-string-to-array.ts @@ -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) ?? [] + ); +}