Javascript tools for dealing with ansi formatted text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// regexp group 1: visible text group 2: ansi codes | |
// eslint-disable-next-line no-control-regex | |
const ansiMatcher = new RegExp("([^\u001B\u009B]*)([\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))|$)", "g") | |
function stripAnsi (s) { | |
return s.replace(ansiMatcher, "$1") | |
} | |
function truncateAnsi (s, len) { | |
let total = 0 | |
return s.replace(ansiMatcher, function (match, nonAnsi, ansi) { | |
if (total === len || 0) { | |
return ansi | |
} | |
if (nonAnsi.length <= len - total) { | |
total += nonAnsi.length | |
return nonAnsi + ansi | |
} | |
nonAnsi = nonAnsi.substr(0, len - total) | |
total = len | |
return nonAnsi + ansi | |
}) | |
} | |
module.exports = { | |
ansiMatcher: ansiMatcher, | |
stripAnsi: stripAnsi, | |
truncateAnsi: truncateAnsi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment