Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Align Text in Browser Console Properly?

I have a task to take values from a prompt and put them like in the picture, but I don’t really understand how to make everything on the same level, for example, so that the ‘|’ was always under the plus, not paying attention to the length of the word.

My result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var arr = []
for (var i = 0; i >= 0; i++) {
    var input = prompt('Enter any value (enter end to complete the operation) ');
    if (input === 'end') break;
    arr[i] = input;
}

console.log(arr)

for (var i = 0; i < arr.length; i++) {
    console.log(`+-----------------+---------------------+ \n|      ${arr[i]}      |`)
}

>Solution :

You can do something like this, but fonts have variable widths so I don’t expect this to work 100%.

var maxLength = 21;
var arr = []
for (var i = 0; i >= 0; i++) {
  var input = prompt('Enter any value (enter end to complete the operation) ');
  if (input === 'end') break;
  arr[i] = input;
}

console.log(arr)

for (var i = 0; i < arr.length; i++) {
  console.log(`+${'-'.repeat(maxLength-1)}+${'-'.repeat(maxLength-1)}+ \n|${' '.repeat((maxLength-arr[i].length)/2)}${arr[i]}${' '.repeat((maxLength-arr[i].length)/2)}|`)
}

enter image description here

For example number 2 is wider than 1 so this happens:
enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading