Skip to content

Commit

Permalink
add strip_ansi string util
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanatkn committed Nov 8, 2024
1 parent 3bcd9ff commit edf2f04
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/lib/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ensure_end,
deindent,
count_graphemes,
strip_ansi,
} from '$lib/string.js';

/* test__truncate */
Expand Down Expand Up @@ -366,3 +367,15 @@ test__count_graphemes('counts graphemes of a string, where compound emoji are on

test__count_graphemes.run();
/* test__count_graphemes */

/* test__strip_ansi */
const test__strip_ansi = suite('strip_ansi');

test__strip_ansi('counts graphemes of a string, where compound emoji are one grapheme', () => {
assert.is(strip_ansi('\x1B[31mred text\x1B[0m'), 'red text');
assert.is(strip_ansi(' \x1B[1;33;40m Yellow on black \x1B[0m '), ' Yellow on black ');
assert.is(strip_ansi('/src/'), '/src/');
});

test__strip_ansi.run();
/* test__strip_ansi */
5 changes: 5 additions & 0 deletions src/lib/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,8 @@ export const plural = (count: number | undefined | null, suffix = 's'): string =
*/
export const count_graphemes = (str: string): number =>
count_iterator(new Intl.Segmenter().segment(str));

/**
* Strips ANSI escape sequences from a string
*/
export const strip_ansi = (str: string): string => str.replaceAll(/\x1B\[[0-9;]*[a-zA-Z]/g, ''); // eslint-disable-line no-control-regex

0 comments on commit edf2f04

Please sign in to comment.