1extern crate ansi_regex;
2use ansi_regex::ansi_regex;
3
4pub fn strip_ansi(string: &str) -> String {
5 ansi_regex().replace_all(string, "").to_string()
7}
8
9#[cfg(test)]
10mod tests {
11 use super::*;
12
13 #[test]
14 fn test_strip_ansi_basic() {
15 let string = "Hello \x1b[1mWorld\x1b[0m!";
16 let stripped_string = "Hello World!";
17
18 assert_eq!(strip_ansi(string), stripped_string);
19 }
20
21 #[test]
22 fn strip_color_from_string() {
23 let string = "\u{001B}[0m\u{001B}[4m\u{001B}[42m\u{001B}[31mBetween \u{001B}[39m\u{001B}[49m\u{001B}[24mColors\u{001B}[0m";
24 let stripped_string = "Between Colors";
25
26 assert_eq!(strip_ansi(string), stripped_string);
27 }
28
29 #[test]
30 fn strip_color_from_ls_command() {
31 let string = "\u{001B}[00;38;5;244m\u{001B}[m\u{001B}[00;38;5;33mls command\u{001B}[0m";
32 let stripped_string = "ls command";
33
34 assert_eq!(strip_ansi(string), stripped_string);
35 }
36
37 #[test]
38 fn strip_reset_setfg_setbg_italics_strike_underline_sequence_from_string() {
39 let string = "\u{001B}[0;33;49;3;9;4mformatters\u{001B}[0m";
40 let stripped_string = "formatters";
41
42 assert_eq!(strip_ansi(string), stripped_string);
43 }
44
45 #[test]
46 fn strip_link_from_terminal_link() {
47 let string = "\u{001B}]8;;https://github.com\u{0007}click\u{001B}]8;;\u{0007}";
48 let stripped_string = "click";
49
50 assert_eq!(strip_ansi(string), stripped_string);
51 }
52}