From 86fa81acb7dfcf1dc3d6f5600cbf427ee44cf722 Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Fri, 8 Jan 2021 00:46:29 +0000 Subject: [PATCH] feat(strings): add stripAnsi(), lengthAnsi() fns --- packages/strings/src/ansi.ts | 22 ++++++++++++++++++++++ packages/strings/src/index.ts | 2 ++ 2 files changed, 24 insertions(+) create mode 100644 packages/strings/src/ansi.ts diff --git a/packages/strings/src/ansi.ts b/packages/strings/src/ansi.ts new file mode 100644 index 0000000000..b6155c45d9 --- /dev/null +++ b/packages/strings/src/ansi.ts @@ -0,0 +1,22 @@ +const RE = /\x1b\[[0-9;]+m/g; + +/** + * Removes all ANSI control sequences from given string. + * + * @example + * ```ts + * stripAnsi("\x1B[32mhello\x1B[0m \x1B[91mworld\x1B[0m!""); + * // 'hello world!' + * ``` + * + * @param x + */ +export const stripAnsi = (x: string) => x.replace(RE, ""); + +/** + * Returns length of `x` excluding any ANSI control sequences (via + * {@link stripAnsi}). + * + * @param x + */ +export const lengthAnsi = (x: string) => stripAnsi(x).length; diff --git a/packages/strings/src/index.ts b/packages/strings/src/index.ts index da5fdb4e5c..8d08ae5868 100644 --- a/packages/strings/src/index.ts +++ b/packages/strings/src/index.ts @@ -1,4 +1,6 @@ export * from "./api"; + +export * from "./ansi"; export * from "./case"; export * from "./center"; export * from "./cursor";