Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created February 13, 2020 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mscalora/f55c83496e0bc47a57c6af3d4ae7defe to your computer and use it in GitHub Desktop.
Save mscalora/f55c83496e0bc47a57c6af3d4ae7defe to your computer and use it in GitHub Desktop.
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