Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created Feb 13, 2020
Embed
What would you like to do?
Javascript tools for dealing with ansi formatted text
// 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