DEV Community

Alwar G
Alwar G

Posted on

Align Strings using PadEnd

padEnd Img
Hi All,

Now we are going to talk about Align Strings using PadEnd as shown in the above image. If you are not familiar with padEnd then read this first.

Ok let's start.

HTML:

<div id="table"></div>
Enter fullscreen mode Exit fullscreen mode

JS:

let stringsMap = {
  Name: 'Alwar G',
  Age: '24',
  'Marital Status': 'single',
  Skills: 'HTML, CSS, JS'
 };
 let objKeys = Object.keys(stringsMap);
 let keysSpace = Math.max(...objKeys.map(el => el.length));
 let table = document.getElementById('table')
 objKeys.forEach((key) => {
   let ele = document.createElement('pre');
   ele.innerHTML = `${key.padEnd(keysSpace)}: ${stringsMap[key]}`;
   table.appendChild(ele);
  });
Enter fullscreen mode Exit fullscreen mode

Here we have strings map to disaplay the details. From the strings map we need to find which key string is the longest string in the keys. For that first we need to get all key strings length. that is

let objKeys = Object.keys(stringsMap);
objKeys.map(el => el.length);
// [4, 3, 14, 6]
Enter fullscreen mode Exit fullscreen mode

After this we should find the longest number from the above array

Math.max(...objKeys.map(el => el.length));
// 14
Enter fullscreen mode Exit fullscreen mode

Now we got the maximum string length. So, we need to align the strings based on this length. Here PadEnd will play a virtual rule. How?πŸ€”
let's see

let table = document.getElementById('table')
objKeys.forEach((key) => {
  let ele = document.createElement('pre');
  ele.innerHTML = `${key.padEnd(keysSpace)}: ${stringsMap[key]}`;
  table.appendChild(ele);
 });
Enter fullscreen mode Exit fullscreen mode

While iterating object, we are creating the pre element and append this element to the table div.

Also we are setting the innerHTML of pre element as ${key.padEnd(keysSpace)}: ${stringsMap[key]}. Here key.padEnd(keysSpace) will make the needed space to make the correct alignment.

Now we got the output.

got it

Thanks for reading. I hope you enjoyed this post.

Top comments (0)