Last active
January 19, 2024 12:52
-
-
Save BeyondMagic/ec2df092848a52fef5475375335b1ea8 to your computer and use it in GitHub Desktop.
Get the real length of a string with hex codes. Useful when looping through a string.
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
// get true length of a a string with colors | |
// this is necessary since javascript counts everything in the string | |
// which is not good when you are looping a string | |
// mainly when you are using it to make it even with the terminal size | |
// you can pass it to String.prototype and remove the test of string | |
const length = str => { | |
//always string | |
if (!str || typeof str !== 'string') | |
return 0; | |
let matches = str.match(/\[\d+m/g); | |
if (matches) | |
matches = matches.join('').length; | |
let lengthHex = 0; | |
const hexs = str.split(''); | |
if (hexs) { | |
for (l of hexs) { | |
if (l === '\x1B') | |
lengthHex++; | |
} | |
} | |
return (lengthHex + matches - str.length) * -1; | |
} | |
// string with hex and color to print in terminal | |
// \x1B or \x1b = hex to color | |
// [7m = color | |
// [0m = reset to normal color | |
const teste = '\x1B[7mteste\x1B[0m'; | |
console.log(teste, teste.length); | |
// > teste 13 | |
console.log(teste, trueLength(teste)); | |
// > teste 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment